Sub topic 4
Storing Numbers: Wrapper Types and Autoboxing
You already know how to make a List<String>. Now suppose you want a list of numbers. Your first try might be List<int>. Java will not compile it. This chapter explains why, what to use instead, and the few traps that come with storing numbers in collections.
Primitives and Objects
Java has two kinds of values.
A primitive is a simple value that is not an object. Java has eight of them: int, long, double, float, short, byte, char, and boolean. A primitive has no methods. It is just the raw value.
An object is an instance of a class. A String is an object. An ArrayList is an object. Objects can have methods, and a variable that holds an object can also hold null, which means "no object at all".
Collections only store objects. A generic type parameter, the <...> part, must name a class. Because int is not a class, List<int> is not allowed.
Wrapper Types
To fix this, Java gives every primitive a matching class. A wrapper type is a class whose job is to hold one primitive value inside an object.
| Primitive | Wrapper type |
|---|---|
| `int` | `Integer` |
| `long` | `Long` |
| `double` | `Double` |
| `float` | `Float` |
| `short` | `Short` |
| `byte` | `Byte` |
| `char` | `Character` |
| `boolean` | `Boolean` |
Most names are the primitive name with a capital letter. Two are different: int becomes Integer, and char becomes Character.
So a list of whole numbers is a List<Integer>, and a list of decimals is a List<Double>.
import java.util.ArrayList;
import java.util.List;
public class WrapperDemo {
public static void main(String[] args) {
List<Integer> scores = new ArrayList<>();
List<Double> prices = new ArrayList<>();
List<Boolean> answers = new ArrayList<>();
scores.add(90);
prices.add(4.99);
answers.add(true);
System.out.println(scores); // [90]
System.out.println(prices); // [4.99]
System.out.println(answers); // [true]
}
}Autoboxing and Unboxing
Look at scores.add(90) above. The value 90 is an int, but the list wants an Integer. It still works because Java converts it for you.
Autoboxing is the automatic conversion from a primitive to its wrapper type. Java "puts the value in a box".
Unboxing is the opposite: the automatic conversion from a wrapper type back to its primitive. Java "takes the value out of the box".
import java.util.ArrayList;
import java.util.List;
public class AutoboxDemo {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>();
nums.add(5); // autoboxing: int 5 becomes Integer 5
nums.add(7);
int first = nums.get(0); // unboxing: Integer 5 becomes int 5
int total = 0;
for (Integer n : nums) {
total = total + n; // unboxing happens inside the math
}
System.out.println(first); // 5
System.out.println(total); // 12
}
}Without autoboxing, you would write nums.add(Integer.valueOf(5)) and nums.get(0).intValue(). Java writes those calls for you behind the scenes.
Autoboxing makes number lists feel almost like arrays of int. But a box is still an object, and objects behave differently from primitives in three places. The rest of this chapter covers those three traps.
Trap 1: remove(int) vs remove(Object)
The List interface has two remove methods:
remove(int index)removes the element at a position.remove(Object o)removes the first element equal to a value.
With a List<String>, there is no confusion. With a List<Integer>, there is. When you call nums.remove(1), which one runs?
Java picks the method that needs no conversion. The value 1 is already an int, so remove(int index) wins. Java removes the element at index 1, not the value 1.
import java.util.ArrayList;
import java.util.List;
public class BoxingDemo {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(List.of(10, 20, 30));
nums.remove(1); // removes the element at index 1
System.out.println(nums); // [10, 30]
nums.remove(Integer.valueOf(10)); // removes the value 10
System.out.println(nums); // [30]
}
}To remove by value, hand Java a real Integer object with Integer.valueOf(10). Then only remove(Object o) fits.
Trap 2: Comparing Wrappers with ==
For primitives, == compares values. For objects, == asks a different question: "Are these the exact same object in memory?" Two separate Integer objects can hold the same number and still not be the same object.
This gets confusing because Java keeps a small cache, a set of ready-made Integer objects for the values -128 to 127. Autoboxing reuses those objects. Outside that range, it usually makes a new object each time.
import java.util.ArrayList;
import java.util.List;
public class CompareDemo {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(List.of(100, 100, 1000, 1000));
System.out.println(list.get(0) == list.get(1)); // true (cached)
System.out.println(list.get(2) == list.get(3)); // usually false
System.out.println(list.get(2).equals(list.get(3))); // true
int a = list.get(2);
int b = list.get(3);
System.out.println(a == b); // true (primitives)
}
}The code "works" with small test numbers and then breaks with real data. The fix is simple: compare wrapper objects with equals, or unbox them into primitives first.
Trap 3: Unboxing null
A wrapper variable can hold null. A primitive cannot. If Java tries to unbox null, there is no number to take out of the box, so it throws a NullPointerException.
import java.util.ArrayList;
import java.util.List;
public class NullUnboxDemo {
public static void main(String[] args) {
List<Integer> values = new ArrayList<>();
values.add(42);
values.add(null); // allowed: a List<Integer> can hold null
Integer boxed = values.get(1);
System.out.println(boxed); // null
try {
int n = values.get(1); // unboxing null
System.out.println(n);
} catch (NullPointerException e) {
System.out.println("Cannot unbox null into an int");
}
}
}The crash happens on the line int n = values.get(1);, even though nothing on that line looks like a method call. The hidden intValue() call is what fails. You will see this again with maps, where looking up a missing key returns null. If a value might be null, keep it in an Integer variable and check it before you do math.
A Note on Speed and Memory
Each Integer is a full object. It takes more memory than a plain int, and boxing and unboxing cost a little time. For lists of a few thousand numbers, you will never notice. For millions of numbers in a tight loop, a plain int[] array can be faster. As a beginner, use the collection that makes your code clear, and think about this only if a program is measurably slow.
| Question | `int` | `Integer` |
|---|---|---|
| Can go in a collection? | No | Yes |
| Can be `null`? | No | Yes |
| Compare with `==`? | Yes, safely | No, use `equals` |
| Has methods? | No | Yes, such as `compareTo` |
Summary
- Collections hold objects, so you use wrapper types like
IntegerandDoubleinstead ofintanddouble. - Autoboxing turns a primitive into its wrapper. Unboxing turns it back. Java does both automatically.
- On a
List<Integer>,remove(1)removes by index. Useremove(Integer.valueOf(1))to remove by value. - Compare wrapper objects with
equals, not==. - Unboxing
nullthrowsNullPointerException.
Exercise
A list is created with List<Integer> ids = new ArrayList<>(List.of(5, 3, 1)); and then the code calls ids.remove(1); What does the list contain afterward, and how would you change the call to remove the value 1 instead?
Show answer
The call removes the element at index 1, which is 3, so the list becomes [5, 1]. To remove the value 1, call ids.remove(Integer.valueOf(1)), which leaves [5, 3].
Exercise
Why can list.get(0) == list.get(1) print true when both elements are 50, but print false when both are 500?
Show answer
The == operator on Integer objects checks whether they are the same object. Java caches Integer objects for values from -128 to 127, so both 50s point to the same cached object. The 500s are usually two separate objects, so == is false. Use equals to compare the values.
Exercise
Given List<Integer> temps = new ArrayList<>(); temps.add(null); which line throws an exception: Integer t = temps.get(0); or int t = temps.get(0); and why?
Show answer
The line int t = temps.get(0); throws a NullPointerException. Java must unbox the Integer into an int, and null has no value to unbox. The line Integer t = temps.get(0); is fine because an Integer variable can hold null.