Search code examples
javahashmapclone

clone() method in hashmap


Working with clone() in hashmap:

HashMap<Integer, String> map = new HashMap<>();

map.put(1, "Raj");
map.put(3, "Kumar");
map.put(2, "Ram");

HashMap map1 = (HashMap) map.clone();

map1.put(7, "Kavin");

System.out.println("Map1: "+map1);
System.out.println("Map: "+map);

This will give the output as,
Map1: {1=Raj, 2=Ram, 3=Kumar, 7=Kavin}
Map: {1=Raj, 2=Ram, 3=Kumar}

But if i try to run in jdk8, it throws compilation error.


Note: HelloWorld.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Program 2:

  HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("Java", 8);
    map.put("Csharp", 5);
    Map<String, Integer> mapClone = (Map<String, Integer>) 
            Collections.checkedMap((Map<String, Integer>)map.clone(),  String.class, Integer.class);

But if i try to run in jdk8, it throws compilation error.


Note: HelloWorld.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

why??...


Solution

  • Note: HelloWorld.java uses unchecked or unsafe operations.

    Note:Recompile with -Xlint:unchecked for details.

    These are just warnings not Compilation Error

    These warning simply means that the compiler can't check that you're using the collection in a type-safe way, using generics.