Questions
What are wrapper classes and why are they useful for ArrayLists? In your answer, include examples of autoboxing and unboxing.
1. Explanations
1.1. What are wrapper classes?
Wrapper classes are some classes in java.lang package, including Boolean, Byte, Character, Short, Integer, Long, Float, and Double, these classes correspond to primitive types boolean, byte, char, short, int, long, float, and double, respectively.
1.1.1. These wrapper classes contain some constants. Specifically, constants are the final static variables in the class, like Integer.MIN_VALUE and Integer.MAX_VALUE.
1.1.2. These wrapper classes contain some methods. First, an essential kind of methods is to convert primitive type value to and from object. For example, the wrapper class Integer has a method Interger.valueOf(), which can convert int value to Integer object:
1 | Integer x = Interger.valueOf(3); |
And it also has a method intValue(), which can retrieve the int value from the Integer object:
1 | int y = x.intValue(); |
Second, another important kind of methods is to convert a string to and from a primitive type. For instance, the wrapper class Integer has a method Integer.parseInt(), which can convert a string to an int value:
1 | int num = Integer.parseInt("123"); |
And it also has a method toString(), which can convert a int value to a string:
1 | String str = Integer.toString(123); |
1.1.3. The above two methods are the most commonly used, and there are other methods in these wrapper classes. For detail, we can refer to the Java API, RUL: https://docs.oracle.com/javase/8/docs/api/
1.2. Why are wrapper classes useful for ArrayLists?
ArrayList
1 | ArrayList<Double> arrayList = new ArrayList<Double>(); |
2. Examples
Autoboxing and unboxing are automatic conversions between a primitive type and the corresponding wrapper class (Eck, 2019). Specifically, autoboxing will automatically wrap a primitive type value in an object type value if the context requires an object type value. Besides, unboxing will automatically convert an object type value to a primitive type value if the context requires a primitive type value.
2.1. Example of autoboxing
Codes:
1 | ArrayList<Double> arrayList = new ArrayList<Double>(); |
Explanation:
The ArrayList
2.2. Example of unboxing
Codes:
1 | ArrayList<Double> arrayList = new ArrayList<Double>(); |
Explanation:
In the above example, we add a Double type value 2.0 into the arrayList by autoboxing. Now, we call the method get(0) to get the first Double value in the arrayList and assign it to a primitive type double variable. This is because the Double value will be automatically converted into a double value, then it can be assigned to the double type variable num.
Word count: 548
References
1.Eck, D. J. (2019). Introduction to Programming Using Java.
http://math.hws.edu/javanotes