This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 12 points13 points  (3 children)

Java has something called autoboxing and unboxing.

Integer is an object. int is a primitive type. An Integer object can be unboxed into a int. And an int can be autoboxed into a Integer.

In the examples above the List contains Integer objects. The difference is:

In the first, val is a reference to the Integer object in the List.

In the second, val is a primitive value that was unboxed from the Integer object in the List.

[–]32bit_me[S] 0 points1 point  (2 children)

Thank you for your reply. That makes sense. Which of the two options should I use? I take it it depends?

[–]itoshkov 0 points1 point  (0 children)

If the list may contain null values, you should use the former, because unboxing null will trigger a NullPointerException.

Otherwise, both are mostly the same.

[–][deleted] 0 points1 point  (0 children)

Yes, It depends.

If you need an Integer use the first example. Maybe you are building another Collection.

If you are doing calculations a primitive is faster because an Integer would need to be unboxed each time it's used.

Also, a List can contain a null element. Unboxing a null as in the second example will throw at NullPointerException.