Search
Calendar
May 2025
S M T W T F S
« Apr    
 123
45678910
11121314151617
18192021222324
25262728293031
Archives

PostHeaderIcon HashMap: beware of autoboxing!

Advice: with Java 5, do not use autoboxing without generics!

Otherwise, you may encounter subtl problems. Consider these code samples:

 package vrac; import java.util.HashMap; import junit.framework.TestCase; public class TestHashMap extends TestCase{ 	public void testAutoboxingIntegerAndLong(){ 		HashMap toto = new HashMap(); 		assertEquals(0, toto.size()); 		toto.put(3, "titi"); 		assertEquals(1, toto.size()); 		assertEquals("titi", toto.get(3)); 		toto.put(new Long(3), "tata"); 		assertEquals(2, toto.size()); 		assertEquals("titi", toto.get(3)); 		assertEquals("tata", toto.get(new Long(3))); 	} 	public void testAutoboxingLongAndLong()	{ 		HashMap toto = new HashMap(); 		assertEquals(0, toto.size()); 		toto.put(3, "titi"); 		assertEquals(1, toto.size()); 		assertEquals("titi", toto.get(3)); 		toto.put(new Integer(3), "tata"); 		assertEquals(1, toto.size()); 		assertEquals("tata", toto.get(3)); 		assertEquals("tata", toto.get(new Integer(3))); 	} } 

In the first case, you can see ambiguities involved by the use of 3, which is an integer and not a long.

If the type used are specified (such as HashMap<Integer, String> toto = new HashMap<Integer, String> ();), no ambiguity may be, no issue is relevant.

Leave a Reply