Search
Calendar
July 2025
S M T W T F S
« Jun    
 12345
6789101112
13141516171819
20212223242526
2728293031  
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