Arrays#
An array holds a fixed number of values of one type:
int[] scores = new int[5]; // five 0s
int[] primes = {2, 3, 5, 7, 11};
String[] names = new String[3]; // three nulls
New arrays are filled with defaults: 0 for numbers, false for boolean, and null for objects such as String.
primes[0] // 2
primes.length // 5: a field, no brackets
primes[5] // ArrayIndexOutOfBoundsException
The Arrays helpers#
import java.util.Arrays;
Arrays.sort(primes); // ascending, in place
Arrays.toString(primes) // "[2, 3, 5, 7, 11]": arrays do not print nicely on their own
Arrays.fill(scores, -1); // every element -1
int[] copy = Arrays.copyOf(primes, primes.length);
Arrays.equals(primes, copy) // true: compares contents
int sum = Arrays.stream(primes).sum(); // 28
System.out.println(primes) prints something like [I@1b6d3586, the array's identity, not its contents. Use Arrays.toString.
Two-dimensional arrays#
int[][] grid = new int[3][4]; // 3 rows of 4 zeros
grid[1][2] = 7;
for (int[] row : grid) {
System.out.println(Arrays.toString(row));
}
int[][] triangle = new int[4][]; // rows of different lengths
for (int i = 0; i < 4; i++) {
triangle[i] = new int[i + 1];
}
ArrayList: a growable list#
When the number of items is not known in advance, use an ArrayList:
import java.util.ArrayList;
import java.util.List;
List<Integer> nums = new ArrayList<>();
nums.add(4); // [4]
nums.add(8); // [4, 8]
nums.add(0, 1); // [1, 4, 8]: insert at position 0
nums.get(1) // 4
nums.set(1, 5); // [1, 5, 8]
nums.remove(Integer.valueOf(8)); // remove the value 8: [1, 5]
nums.remove(0); // remove position 0: [5]
nums.size() // 1
nums.contains(5) // true
Adding to the end is fast; inserting or removing near the front shifts everything after it.
Integer, not int#
Lists hold objects, so a list of numbers is List<Integer>, not List<int>. Java converts between int and Integer automatically (boxing), which hides two traps:
removeis ambiguous.nums.remove(1)removes position1. To remove the value 1, writenums.remove(Integer.valueOf(1)).==compares objects. TwoIntegervalues above 127 are often different objects, soa == bcan befalsewhen they are equal. Usea.equals(b), or compare asint.
Sorting lists#
import java.util.Collections;
Collections.sort(nums); // ascending
nums.sort(Collections.reverseOrder()); // descending
words.sort((a, b) -> a.length() - b.length()); // by length
The last form passes a lambda that says which of two items comes first: negative if a should come first, positive if b should.
Converting#
// list to int[] (the judge often wants an array back)
int[] arr = nums.stream().mapToInt(Integer::intValue).toArray();
// int[] to list
List<Integer> list = new ArrayList<>();
for (int x : arr) list.add(x);
// fixed list of known values
List<String> days = List.of("Mon", "Tue", "Wed"); // cannot be changed
Key points#
- Arrays have a fixed size,
lengthwith no brackets, and default values. - Print arrays with
Arrays.toString; sort withArrays.sort. ArrayListgrows withadd; read withget, change withset.- Lists hold
Integer: watchremove(int)and==on boxed values. Collections.sortorlist.sortsorts; a lambda changes the order.
That completes the Java basics. Try the practice problems below, then the Learn track to put arrays, lists and maps to work on real algorithms.