Wrapper Classes
| English | Chinese | Pinyin |
|---|---|---|
| wrapper class | 包装类 | bāo zhuāng lèi |
| autoboxing | 自动装箱 | zì dòng zhuāng xiāng |
| unboxing | 自动拆箱 | zì dòng chāi xiāng |
Boxing a primitive
- Some Java structures (like
ArrayList) hold objects, not primitives. - A wrapper class 包装类 wraps a primitive in an object:
Integerwrapsint,Doublewrapsdouble. Integer boxed = Integer.valueOf(5);puts theint5inside an object.- Wrappers let primitives live where only objects are allowed.
Autoboxing and unboxing
- Java converts automatically — autoboxing 自动装箱 and unboxing 自动拆箱.
Integer x = 5;autoboxes5;int y = x;unboxes it back.- So
list.add(5)works even though the list holdsIntegerobjects. - You rarely write
Integer.valueOfby hand — autoboxing does it.
Why ArrayList needs them
ArrayList<Integer>holdsIntegerobjects, because generics require a reference type.- You can't write
ArrayList<int>— primitives aren't objects. - Autoboxing lets you add and read plain
ints conveniently. Double,Boolean, etc. play the same role for their primitives.
Compare wrappers with equals
- Two
Integerobjects should be compared with.equals(), not==. ==compares references;.equals()compares the wrapped values.- (Java caches small Integers, so
==sometimes seems to work — don't rely on it.) - The same "use
.equals()for objects" rule fromStringapplies here.
Wrappers are objects, so compare their values with .equals(), not ==. == tests reference identity; for two Integer objects with the same value it can be false. And you can't parameterize a collection with a primitive — it's ArrayList<Integer>, never ArrayList<int>. Autoboxing bridges the gap so you can still add plain ints.
Wrappers with an ArrayList:
ArrayList<Integer> nums = new ArrayList<Integer>();nums.add(5);— theint5is autoboxed into anInteger.int first = nums.get(0);— theIntegeris unboxed back toint.
A wrapper class (Integer, Double, Boolean) wraps a primitive in an object so it can go where objects are required — like an ArrayList<Integer> (you can't write ArrayList<int>). Autoboxing and unboxing convert automatically. Compare wrapper objects with .equals(), not ==.
Autoboxing and unboxing
int ↔ Integer conversions happen automatically.
Which wrapper class wraps an int?
Integer wraps int; Double wraps double.
Why must an ArrayList of ints be declared ArrayList
You can't write ArrayList
Two Integer objects should be compared with...
Wrappers are objects — use .equals() for their values.
In nums.add(5), the int 5 is automatically boxed into an Integer (autoboxing).
Autoboxing converts the primitive to a wrapper object.
A class that wraps a primitive in an object is a ___ class (one word).
Integer, Double, Boolean are wrapper classes.