We know we can use an array to store a bunch of values, but perhaps the biggest issue with arrays
is that we cannot resize them, unless we create a copy of the array and change the length of that
copy. Because of this, a type called ArrayList exists — it works like a dynamic array.
To use an ArrayList, import it from java.util.ArrayList. To declare one, use the ArrayList
keyword followed by a pair of angle brackets containing the type of data to be stored (typed in
full, since it must be a reference type rather than a primitive), then the name of the list, then
assign it to a new object of the ArrayList class.
import java.util.ArrayList;import java.util.Comparator; // we use this for the sorting
class Main { public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(1); // adding a value to an arraylist numbers.add(2); numbers.add(3); numbers.add(4); numbers.add(5);
numbers.remove(4); // removes the element at index 4 numbers.remove(Integer.valueOf(4)); // removes the element with value 4 from the arraylist
numbers.clear(); // clears everything, making it an empty arraylist
numbers.indexOf(1); // gets the index of a value in the arraylist
numbers.set(1, 30); // updates the element at index one with 30
numbers.sort(Comparator.naturalOrder()); // sorts the arraylist in ascending order numbers.sort(Comparator.reverseOrder()); // sorts the arraylist in descending order
System.out.println(numbers.size()); // prints the size of the arraylist
System.out.println(numbers.contains(1)); // true if the arraylist contains the integer 1
System.out.println(numbers.isEmpty()); // true if the arraylist is empty
System.out.println(numbers.toString()); // convert it to string to print it out System.out.println(numbers.get(2)); // prints the element at index 2 }}ArrayLists are dynamic arrays, so you can add as many elements as you want.
For-each loop
class Main { public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(1); numbers.add(2); numbers.add(3); numbers.add(4); numbers.add(5);
numbers.forEach(number -> { System.out.println(number * 2); }); System.out.println(numbers.toString()); }}For each number in the numbers arraylist, we double it and print it out.