Autoboxing and Unboxing
Primitive type vs. Wrapper class
A wrapper class is just a wrapper of the corresponding primitive type, the Object representation of primitive type values.
primitive | wrapper |
---|---|
boolean | Boolean |
byte | Byte |
char | Character |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
Similar to String, all the wrapper class objects are IMMUTABLE - internal values can not be changed afer initialization.
Why we need Wrapper Class?
- Generic type can not be primitive type, List< Integer>, there and not be List< int>
- It can help provide useful functionalities and contracts (json serializer : obj -> json)
How do you represent a "not existed" int value? null.
So prefer primitive type to wrapper classes
Autoboxing
Autoboxing is the automatic conversion that Java compoler makes between the primitive type and their corresponding object wrapper classes.
List <Integer> integerList = new ArrayList<>();
for (int i = 0; i < 50; i++) {
integerList.add(i); // ==> integerList.add(Integer.valueOf(i));
}
Unboxing
unboxing is the reverse operation of autoboxing. +,-,*,/,>,< ,>=,...only appled to primitive type.
Integer a = 4; // autoboxing => Integer a = Integer.valueOf(4);
a += 4;
a++;
// int temp = a.intValue(); temp++;
// a = Integer.valueOf(temp);
/* Integer is immutable, the int value of the Integer object can never change*/
Excercises
== both operand can be Object type and it is comparing if the two references are pointed to the same Obejct.
Integer a = 5; //autoboxing
int b = 5; //primitive
a == b; // true
Integer c = 5;
a == c; // true
a = 129;
c = 129;
a == c; // false
- Note: Integer class cache the Integer Object eith value from -128 to 127, so every time an Integer object within this range is needed, it will always return the corresponding object.
- The unboxing is done only when it is necessary, for example, a > b. Be very careful about using "=="
- int[] vs. Integer[] They are totally different types, and there is no auto conversion directly between them.
Integer[] objArray = new Integer[5];
int[] array = objArray; // compile error!!!
when implement your Comparator or override equals()
Keep in Mind:
- be very careful if you see "==" on Object type.
- It could overflow. (e.g. return i1-i2)
class MyComparator implements Comparator<Long> {
@Override
public int compare(Long l1, Long l2) {
if (l1 < l2) {
return -1;
} else if (l2 > l2) {
return 1;
}
return 0;
}
}