HashMap deep copy Vs simple copy

Question: Many times we ask same question again and again, year after year.
The best way to understand is run the following code.


import java.util.HashMap;
import java.util.Iterator;

public class HashMapTest
{
  public static void main( final String[] args )
  {
    testReference();
    testDeepCopy();
  }

  private static void testDeepCopy()
  {
    System.out.println( "Deep Copy Test" );
    final HashMap<Integer, String> data1 = new HashMap<Integer, String>();
    data1.put( new Integer( "1" ), "one" );
    data1.put( new Integer( "2" ), "two" );

    final HashMap<Integer, String> data2 = new HashMap<Integer, String>( data1 );
    printHashMap( data1, "data1" );
    printHashMap( data2, "data2" );

    System.out.println( "Remove data in data2" );

    data1.remove( new Integer( 2 ) );
    printHashMap( data1, "data1" );
    printHashMap( data2, "data2" );
  }

  private static void testReference()
  {
    System.out.println( "Simple Copy Test" );
    final HashMap<Integer, String> data1 = new HashMap<Integer, String>();
    data1.put( new Integer( "1" ), "one" );
    data1.put( new Integer( "2" ), "two" );

    final HashMap<Integer, String> data2 = data1;
    printHashMap( data1, "data1" );
    printHashMap( data2, "data2" );

    System.out.println( "Remove data in data2" );

    data1.remove( new Integer( 2 ) );
    printHashMap( data1, "data1" );
    printHashMap( data2, "data2" );
  }

  private static void printHashMap( final HashMap<Integer, String> map,
    final String message )
  {
    System.out.println( "---- " + message + " Begin ----" );
    final Iterator iterator = map.keySet().iterator();

    while ( iterator.hasNext() ) {
      final Integer key = (Integer)iterator.next();
      final String value = map.get( key );

      System.out.println( key + " " + value );
    }
    System.out.println( "---- " + message + " End ----" );
  }

}

Result:
Simple Copy Test
—- data1 Begin —-
1 one
2 two
—- data1 End —-
—- data2 Begin —-
1 one
2 two
—- data2 End —-
Remove data in data2
—- data1 Begin —-
1 one
—- data1 End —-
—- data2 Begin —-
1 one
—- data2 End —-
Deep Copy Test
—- data1 Begin —-
1 one
2 two
—- data1 End —-
—- data2 Begin —-
1 one
2 two
—- data2 End —-
Remove data in data2
—- data1 Begin —-
1 one
—- data1 End —-
—- data2 Begin —-
1 one
2 two
—- data2 End —-

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s