</>CodexBash
Java
JavaBeginner12 min

Arrays and ArrayList

Fixed-size arrays and their defaults, the Arrays helpers, two-dimensional arrays, the growable ArrayList with its boxing pitfalls, and sorting both.

Adding and removing in a liststep 1/5
72
88
95
size = 3
A list of three scores, at positions 0, 1 and 2.

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:

  • remove is ambiguous. nums.remove(1) removes position 1. To remove the value 1, write nums.remove(Integer.valueOf(1)).
  • == compares objects. Two Integer values above 127 are often different objects, so a == b can be false when they are equal. Use a.equals(b), or compare as int.

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, length with no brackets, and default values.
  • Print arrays with Arrays.toString; sort with Arrays.sort.
  • ArrayList grows with add; read with get, change with set.
  • Lists hold Integer: watch remove(int) and == on boxed values.
  • Collections.sort or list.sort sorts; 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.

Practise it

The same idea, in the order it is worth meeting it.

  1. Not startedRunning sumEasy
  2. Not startedMove the zeroes to the endEasy
  3. Not startedContains duplicateEasy
Create a free account to track your progress