Collections hold objects, not primitives
You can't write ArrayList<int>. Collections can only hold objects, so every primitive type has a wrapper class that wraps it in an object:
| Primitive | Wrapper class |
|---|---|
int | Integer |
double | Double |
boolean | Boolean |
char | Character |
long | Long |
Java converts between them automatically. This is called autoboxing (and unboxing back):
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<>();
nums.add(40);
nums.add(15);
nums.add(25);
int total = 0;
for (int n : nums) {
total += n;
}
System.out.println(nums + " add up to " + total);
System.out.println(Integer.MAX_VALUE);
}
}Output
[40, 15, 25] add up to 80 2147483647
The remove trap
With a list of Integers, remove(1) removes position 1, not the number 1. To remove the value, wrap it: remove(Integer.valueOf(1)):
import java.util.ArrayList;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> a = new ArrayList<>(Arrays.asList(5, 9, 1));
a.remove(1);
System.out.println(a);
ArrayList<Integer> b = new ArrayList<>(Arrays.asList(5, 9, 1));
b.remove(Integer.valueOf(1));
System.out.println(b);
}
}Output
[5, 1] [5, 9]
Tip:
new ArrayList<>(Arrays.asList(5, 9, 1))is a quick way to make a list that already has values.
Common mistake: Compare two
Integerobjects with.equals(), not==– just like Strings.