Autoboxing and Wrapper Classes
Part of: ArrayList
Objects Only An ArrayList can only store objects , never primitive types like int, double, or boolean. You cannot write ArrayList<int . Instead Java provides wrapper classes that wrap a primitive in an object: - int - Integer - double - Double - boolean - Boolean So you write ArrayList<Integer or ArrayList<Double . Autoboxing Autoboxing is the automatic conversion from a primitive to its wrapper. Unboxing is the reverse. The compiler inserts these conversions for you: Because of autoboxing, you can mostly treat ArrayList<Integer as if it held plain ints. But the values are really Integer objects under the hood. Pitfalls to Know - Comparing with == : Comparing two Integer objects with == may give wrong results because it compares references, not values. Use .equals() or unbox to int first. - Null unboxing : Unboxing a null Integer throws a NullPointerException. - remove(int) trap : As seen earlier, list.remove(5) on an Integer list removes index 5, not the value 5, precisely because the int overload is preferred over autoboxing. Summary - ArrayList holds objects; use wrapper classes for primitives. - Autoboxing/unboxing convert automatically between int and Integer. - Beware == on w
Challenge: Sum and Average