Search
Calendar
June 2025
S M T W T F S
« May    
1234567
891011121314
15161718192021
22232425262728
2930  
Archives

PostHeaderIcon HashMap.put(null, toto)

Question: does Java’s HashMap accept null as a key?

I thought it did not, but the answer is: yes. Better than speechs, a code sample proves it:

 package vrac; import java.util.HashMap; import junit.framework.TestCase; public class TestHashMap extends TestCase{ 	public void testHashMap(){ 		HashMap toto = new HashMap(); 		toto.put("tata", "titi"); 		assertEquals("titi", toto.get("tata")); 		toto.put(null, "tutu"); 		assertEquals("tutu", toto.get(null)); 		assertTrue(toto.keySet().contains(null)); 		assertTrue(toto.values().contains("tutu")); 	} } 

All JUnit tests above are OK, there is no failure and no error.

Leave a Reply