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.