Java 1.5 has made auto boxing unboxing redundant. The IDE that I use tells me where it is redundant. Recently, I came across a scenario where, I had a list of Integers and from this list, I wanted to remove a value. I can do it this way.

list.remove(new Integer(-1));

This will remove the Integer of value -1 from the list. My IDE started screaming that boxing is unnecessary. For some strange reason this did not seem right to me. So I decided to check the List API. I came across 2 signatures for the remove method.

boolean remove(Object o); – This removes the object o from the list

E remove(int index); – The value corresponding to the index is removed

So, if I do not box the Integer, my whole logic goes for a toss. The value I pass, will be treated as the index rather than the value.

Moral : Do not blindly remove boxing from legacy code. Take a minute, see the API specs and only if everything seems right then remove the boxing.

Advertisements