Printing a whole array
Printing an array directly gives a strange code. Arrays.toString prints it nicely:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] nums = {5, 2, 9, 1};
System.out.println(Arrays.toString(nums));
}
}Output
[5, 2, 9, 1]
Common Arrays tools
| Tool | Does |
|---|---|
Arrays.toString(a) | turns the array into readable text |
Arrays.sort(a) | sorts the array from small to big (changes it) |
Arrays.fill(a, v) | sets every element to v |
Arrays.copyOf(a, n) | a new array with the first n elements |
Arrays.equals(a, b) | true if both arrays hold the same values |
Arrays.binarySearch(a, v) | index of v in a sorted array |
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] nums = {5, 2, 9, 1};
Arrays.sort(nums);
System.out.println(Arrays.toString(nums));
System.out.println(Arrays.binarySearch(nums, 5));
String[] names = {"Ravi", "Asha", "Meera"};
Arrays.sort(names);
System.out.println(Arrays.toString(names));
int[] zeros = new int[4];
Arrays.fill(zeros, 7);
System.out.println(Arrays.toString(zeros));
}
}Output
[1, 2, 5, 9] 2 [Asha, Meera, Ravi] [7, 7, 7, 7]
Copying an array the right way
b = a does not copy an array – both names point to the same lockers:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a = {1, 2, 3};
int[] same = a;
int[] copy = Arrays.copyOf(a, a.length);
a[0] = 99;
System.out.println(Arrays.toString(same));
System.out.println(Arrays.toString(copy));
}
}Output
[99, 2, 3] [1, 2, 3]
Common mistake: Changing
aalso changedsame, because they are the same array. UseArrays.copyOfto get a real, separate copy.