ArrayList
, int
An ArrayList
contains many elements. But in Java 8 it cannot store values. It can hold classes (like Integer) but not values (like int
).
Int
notesTo place ints in ArrayList
, we must convert them to Integers. This can be done in the add()
method on ArrayList
. Each int
must added individually.
Here we have an int
array. It has 3 values in it. We create an ArrayList
and add those ints as Integers in a for
-loop.
add()
method receives an Integer. And we can pass an int
to this method—the int
is cast to an Integer.import java.util.ArrayList; public class Program { public static void main(String[] args) { int[] ids = {-3, 0, 100}; ArrayList<Integer> values = new ArrayList<>(); // Add all the ints as Integers with add. // ... The ints are cast to Integer implicitly. for (int id: ids) { values.add(id); } System.out.println(values); // The collections have the same lengths. System.out.println(values.size()); System.out.println(ids.length); } }[-3, 0, 100] 3 3
For
-loopWe can use a simpler syntax to loop over elements—the for
-each loop does not have an index variable. This improves readability. But it reduces flexibility in the loop.
for
-each loop syntax, which omits the index from the Java code—this is simpler.for
-loop syntax, which includes the index variable, and loop up to size()
.import java.util.ArrayList; public class Program { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); list.add(2); list.add(3); list.add(7); // Version 1: use for-each loop. for (int value : list) { System.out.println("FOR 1: " + value); } // Version 2: use for-loop. for (int i = 0; i < list.size(); i++) { System.out.println("FOR 2: " + list.get(i)); } } }FOR 1: 2 FOR 1: 3 FOR 1: 7 FOR 2: 2 FOR 2: 3 FOR 2: 7
Count
, clearThe ArrayList
is used in many programs. But in most places, it is used in a similar way: we instantiate, add elements, and access data.
ArrayList
—diamond inference syntax is on the right side. We add 3 elements in statements.size()
. This returns the number of elements in the collection (here it is 3).clear()
to empty the ArrayList
, and then print its size again. The ArrayList
is empty.import java.util.ArrayList; public class Program { public static void main(String[] args) { // Part 1: create new ArrayList. // ... Add 3 elements. ArrayList<Integer> elements = new ArrayList<>(); elements.add(10); elements.add(15); elements.add(20); // Part 2: get count by calling size. System.out.println("Count: " + elements.size()); // Part 3: clear and print size. elements.clear(); System.out.println("Count: " + elements.size()); } }Count: 3 Count: 0
IndexOf
We use the indexOf
and lastIndexOf
methods to find indexes. IndexOf
searches from the beginning. LastIndexOf
searches from the end.
ArrayList
and add 5 elements. It contains 2 elements with the value 100.IndexOf
and lastIndexOf
find different indexes because they search in different ways.import java.util.ArrayList; public class Program { public static void main(String[] args) { // Part 1: create ArrayList. ArrayList<Integer> list = new ArrayList<>(); list.add(101); list.add(100); list.add(99); list.add(100); list.add(99); // Part 2: search for values. int index = list.indexOf(100); int lastIndex = list.lastIndexOf(100); int notFound = list.indexOf(200); // Part 3: display results. System.out.println("INDEX: " + index); System.out.println("LASTINDEX: " + lastIndex); System.out.println("NOTFOUND: " + notFound); } }INDEX: 1 LASTINDEX: 3 NOTFOUND: -1
SubList
This returns a view of the ArrayList
. We can loop over the returned List
, or access its elements, using a zero-based index. So the first element in the sub-list is at index 0.
subList()
is the first index of the range we want to access from the ArrayList
.ArrayList
.set()
an element in the sub-list to a value, this is reflected in the original list. The indexes are automatically translated.import java.util.ArrayList; import java.util.List; public class Program { public static void main(String[] args) { // ... Add 5 integers to an ArrayList. ArrayList<Integer> list = new ArrayList<>(); list.add(5); list.add(10); list.add(15); list.add(20); list.add(25); // ... Get sub list from 1 to 3. List<Integer> sub = list.subList(1, 3); // ... Display sub list. for (int value : sub) { System.out.println(value); } // ... Set the first element in "sub" to -1. // This is reflected in the original ArrayList. sub.set(0, -1); System.out.println(list.get(1)); } }10 15 -1
Collections.min
, maxMany static
methods in the Collections class
can be used on an ArrayList
. Here we use two simple ones: min and max.
ArrayList
) and returns the value of the smallest element.import java.util.ArrayList; import java.util.Collections; public class Program { public static void main(String[] args) { // Create ArrayList. ArrayList<Integer> list = new ArrayList<>(); list.add(10); list.add(1); list.add(100); list.add(5); // Min and max. int minimum = Collections.min(list); int maximum = Collections.max(list); System.out.println(minimum); System.out.println(maximum); } }1 100
Collections.addAll
With this we add many elements to an ArrayList
at once. The second argument is either an array of the elements to add, or those elements as arguments.
ArrayList
. We then add 2 more elements with addAll
.import java.util.ArrayList; import java.util.Collections; public class Program { public static void main(String[] args) { ArrayList<Integer> values = new ArrayList<>(); Integer[] array = { 10, 20, 30 }; // Add all elements in array to ArrayList. Collections.addAll(values, array); // Display. for (int value : values) { System.out.print(value); System.out.print(" "); } System.out.println(); // Add more elements. Collections.addAll(values, 40, 50); // Display. for (int value : values) { System.out.print(value); System.out.print(" "); } } }10 20 30 10 20 30 40 50
ToArray
The toArray
method copies an ArrayList
's elements to an array. It has two versions—one returns an Object array and requires casting. This version, though, returns a typed array.
toArray
method will allocate a new array and return its reference unless it receives a large enough array.toArray
by passing it an empty array of the matching type. It then returns a correctly-sized array.import java.util.ArrayList; import java.util.List; public class Program { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); list.add(7); list.add(8); list.add(9); // Create an empty array and pass to toArray. Integer[] array = {}; array = list.toArray(array); // Our array now has the ArrayList's elements. for (int elem : array) { System.out.println(elem); } } }7 8 9
We cannot specify int
as the type of an ArrayList
. An int
is not a "ReferenceType." Instead we must use Integer—and add only Integers to this collection.
import java.util.ArrayList; public class Program { public static void main(String[] args) { // This does not compile. // ... Integer must be used, not int. ArrayList<int> test = new ArrayList<>(); } }Exception in thread "main" java.lang.Error: Unresolved compilation problem: Syntax error, insert "Dimensions" to complete ReferenceType at Program.main(Program.java:8)
AddAll
errorWe cannot pass an int
array to the Collections.addAll
method to add Integers to an ArrayList
. An Integer array can be used.
int
to Integer. A for
-loop with add()
is effective.import java.util.ArrayList; import java.util.Collections; public class Program { public static void main(String[] args) { int[] ids = {-3, 0, 100}; ArrayList<Integer> values = new ArrayList<>(); // This does not compile. // ... Integer is not the same as int. Collections.addAll(values, ids); } }Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method addAll(Collection<? super T>, T...) in the type Collections is not applicable for the arguments (ArrayList<Integer>, int[]) at Program.main(Program.java:11)
What is an Integer? And why cannot we use int
in an ArrayList
? An Integer is a reference type (a class
). An int
is a value.
ArrayList
requires, in its implementation, a reference type. So int
is not allowed.With the Integer class
, we store ints in an ArrayList
. We cannot use int
directly, and this limitation introduces some complexity to our programs.