Monday, May 30, 2011

If we trying to add key-value pairs to HashMap with duplicate key, what does it returns?




HashMap map = new HashMap();
map.put( new Integer( 2 ), "two" );
Object value = map.put( new Integer( 4 ), "four" );
if ( value != null )
      System.out.println( "value: " + value + "\tUpdates with new 4." );
else
      System.out.println( "Added 4." );
System.out.println( map );
System.out.println();
value = map.put( new Integer( 4 ), "FOUR2" );
if ( value != null )
      System.out.println( "value: " + value + "\tUpdates the new value of 4." );
else
      System.out.println( "Added 4." );
System.out.println( "map = " + map );
System.out.println();

HashMap overrides the new value for the existing key; and doesn’t throw exception.
put( ) returns the Object which will have the old value for the same existing key.