Sub topic 10
Wrappers in Generics and Collections, Including List.remove
This chapter assumes you know the primitive types, the basics of classes and objects, the difference between == and equals on objects, and simple use of List and Map with generics. It also assumes you have seen autoboxing and unboxing, covered earlier in this tutorial. Here you will see where those conversions happen in collections, and which bugs they cause.
Why generics need wrapper classes
A generic type argument must be a reference type. List<int> does not compile, but List<Integer> does. Generics are implemented by type erasure. At runtime a List<Integer> is a plain List that stores Object references, so a primitive int has nowhere to live. A wrapper object such as Integer is a real object, so it can be stored.
Autoboxing hides this from your source code. The compiler inserts the conversions around every call that crosses the boundary between primitives and the collection.
import java.util.ArrayList;
import java.util.List;
public class GenericsNeedReferences {
public static void main(String[] args) {
// List<int> broken = new ArrayList<>(); // compile error: type argument cannot be primitive
List<Integer> scores = new ArrayList<>();
scores.add(90); // compiled as scores.add(Integer.valueOf(90))
scores.add(75);
int total = 0;
for (int s : scores) { // each element is unboxed with intValue()
total += s;
}
System.out.println(total);
}
}This prints 165. The loop variable is an int, so each element is unboxed. If any element were null, the loop would throw NullPointerException. A List<Integer> can hold null, and an int cannot.
Where boxing and unboxing appear in collection code
Every method that takes or returns the element type is a conversion point.
| Code | What the compiler does |
|---|---|
| `list.add(5)` | Boxes `5` with `Integer.valueOf(5)` |
| `int x = list.get(0)` | Unboxes with `intValue()` and can throw `NullPointerException` |
| `list.contains(5)` | Boxes `5` to an `Integer`, then calls `equals` on elements |
| `map.put("a", 1)` | Boxes the value |
| `int n = map.get("a")` | Unboxes, and throws if the key is missing |
| `list.set(0, list.get(0) + 1)` | Unboxes, adds, and boxes again |
The last row allocates a new Integer for any result outside the cache range. Each wrapper holds an immutable value, so you cannot increment an element in place.
Maps and the missing-key trap
Map.get returns null when the key is absent. With a Map<String, Integer>, that null is a reference, and it is harmless until you assign it to an int or use it in arithmetic.
The classic counting loop shows the problem:
import java.util.Map;
import java.util.TreeMap;
public class WordCount {
public static void main(String[] args) {
String[] words = {"a", "b", "a", "c", "a", "b"};
Map<String, Integer> counts = new TreeMap<>();
for (String w : words) {
// Broken on the first occurrence of a word:
// counts.put(w, counts.get(w) + 1); // counts.get(w) is null, unboxing throws
counts.merge(w, 1, Integer::sum); // inserts 1 if absent, otherwise adds
}
System.out.println(counts);
}
}This prints {a=3, b=2, c=1}. There are three safe ways to handle a missing key:
getOrDefault(key, 0)supplies a fallback when the key is absent. It returns the stored value when the key is present, even if that value isnull.merge(key, 1, Integer::sum)combines the update and the default in one call.- Assign the result of
getto anIntegervariable and test it fornullbefore unboxing.
A map can also contain a key whose value is null. In that case containsKey returns true while get returns null. If you need to tell the two cases apart, use containsKey.
The List.remove overloads
List declares two methods named remove:
remove(int index)removes the element at a position and returns it.remove(Object o)removes the first element equal tooand returns aboolean.
For a List<Integer>, a call such as list.remove(1) is ambiguous to a reader but not to the compiler. The compiler looks at the static type of the argument. An int argument matches remove(int) exactly. No boxing is needed, so that overload wins.
import java.util.ArrayList;
import java.util.List;
public class RemoveChoices {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(List.of(10, 20, 30, 1));
list.remove(1); // int: removes the element at index 1 (the value 20)
System.out.println(list); // [10, 30, 1]
list.remove(Integer.valueOf(1)); // Integer: removes the value 1
System.out.println(list); // [10, 30]
int target = 30;
list.remove((Object) target); // cast to Object picks remove(Object)
System.out.println(list); // [10]
}
}In the list [10, 20, 30, 1], the value 1 and the index 1 are different things. Which one gets removed depends only on the argument's declared type. A variable declared int removes by index, and a variable declared Integer removes by value.
The following diagram shows how the compiler decides.
Other collections do not have this problem. Set<Integer> and Collection<Integer> have only remove(Object), so set.remove(1) boxes the 1 and removes the value.
Boxing, widening and the wrong wrapper type
Boxing converts an int to an Integer, and nothing else. It never converts an int to a Long. A List<Long> therefore behaves surprisingly when you pass int literals to methods that take Object.
import java.util.ArrayList;
import java.util.List;
public class WrongWrapper {
public static void main(String[] args) {
List<Long> ids = new ArrayList<>(List.of(10L, 20L, 30L));
System.out.println(ids.contains(30)); // false: 30 boxes to Integer, never equals Long 30
System.out.println(ids.contains(30L)); // true
ids.remove(10L); // phase 2: boxes to Long, removes the value 10
System.out.println(ids); // [20, 30]
ids.remove(0); // int matches remove(int) exactly: removes index 0
System.out.println(ids); // [30]
}
}The contains(30) call compiles because contains accepts any Object. It always returns false here, because Integer.equals and Long.equals return false for a different wrapper class. The same applies to Map<Long, String>.get(1), which returns null for every key. ids.remove(10L) works because a long argument cannot narrow to int. Java then tries boxing and finds remove(Object), as described in the overload resolution chapter.
The fix is to match literal types to the element type. Use 30L for a Long collection, 1.0 for Double, and 'x' for Character.
Equality inside collections
Collections never use == on elements. contains, indexOf, remove(Object), and HashMap key lookup all call equals (plus hashCode for hashed collections). That is why a List<Integer> containing 1000 still reports contains(1000) as true, even though two separate Integer objects are involved.
The bug appears when you compare elements yourself:
List<Integer> a = List.of(1000, 5);
List<Integer> b = List.of(1000, 5);
boolean sameFirst = a.get(0) == b.get(0); // usually false: two Integer objects
boolean sameFirstOk = a.get(0).equals(b.get(0)); // trueList.of(1000, ...) boxes each literal separately, so the first elements are different objects. The comparison with == works for small values only because of the cache. a.equals(b) on the lists is true, because List.equals compares elements with equals.
The same rule applies to comparators. Prefer Integer.compare(x, y) or Comparator.naturalOrder(). The shortcut (x, y) -> x - y can overflow for large values, and (x, y) -> x == y ? 0 : ... suffers from the reference problem above.
Converting between arrays, primitives and lists
Generic methods accept only reference types, so an int[] is not a T[]. A well-known mistake follows from this:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class ArrayToList {
public static void main(String[] args) {
int[] raw = {3, 1, 2};
List<int[]> wrong = Arrays.asList(raw); // T is int[], so the list holds one element
System.out.println(wrong.size()); // 1
List<Integer> right = Arrays.stream(raw) // IntStream
.boxed() // Stream<Integer>
.collect(Collectors.toList());
Collections.sort(right);
System.out.println(right); // [1, 2, 3]
int[] back = right.stream().mapToInt(Integer::intValue).toArray();
System.out.println(back.length); // 3
}
}Arrays.asList(raw) treats the whole array as a single object. With Integer[] it would produce a list of three elements. To go from int[] to List<Integer>, use boxed(). To go back, use mapToInt(Integer::intValue), which unboxes each element and builds a primitive array.
Practical guidelines
- Use
List<Integer>andMap<K, Integer>when you need a collection. Useint[]or a primitive stream for large numeric work. Each boxed element costs an object header plus a reference, and the performance chapter covers the cost. - Never assign
map.get(key)straight to a primitive unless you know the key exists. PrefergetOrDefaultormerge. - Make the type of
removearguments explicit:remove(Integer.valueOf(x))for a value,remove(index)for a position. - Match literals to the element type (
30LforLong), becausecontains,indexOf, andMap.getcompile with anyObjectand quietly return "not found". - Compare elements with
equalsorInteger.compare, never==. - Remember that
nullcan be stored in most collections.List.ofandMap.ofrejectnull, butArrayListandHashMapaccept it, and every later unboxing of such an element throws.
Exercise
Given List<Integer> nums = new ArrayList<>(List.of(5, 0, 7, 2)); and int i = 2;, what is nums after nums.remove(i);, and what single change makes the call remove the value 2 instead? What happens if you then call nums.contains(2L)?
Show answer
nums.remove(i) has an int argument, so it picks remove(int index) and removes the element at index 2. nums becomes [5, 0, 2]. To remove the value 2, call nums.remove(Integer.valueOf(i)) (or nums.remove((Object) i)), which selects remove(Object). The call nums.contains(2L) returns false, because 2L boxes to a Long, and Integer.equals(Long) is always false.
Exercise
This method throws NullPointerException the first time it sees a new name. Rewrite the body of the loop so it counts correctly without any if statement.
Map<String, Integer> tally = new HashMap<>();
for (String name : names) {
tally.put(name, tally.get(name) + 1);
}
Show answer
tally.get(name) returns null for a name that has not been seen, and + 1 unboxes it. Replace the body with tally.merge(name, 1, Integer::sum);. Using tally.put(name, tally.getOrDefault(name, 0) + 1); also works. Both supply a starting value instead of unboxing null.