15 March 2011

[Technote] Caution for Java auto-unboxing

Auto unboxing does not work with == or !=.

For example:

Two List<Integer> a and b, a.get(0) == b.get(0) -- does not unbox. Instead, it does an == pointer comparison between the two Integer objects.

To get what you want, you will do the following:

Use a.get(0).intValue() == b.get(0).intValue() to force the conversion to int. Or you could write a.get(0).equals(b.get(0)) which works for String, Integer, etc.

No comments: