简体   繁体   中英

what is the difference between clone method or copy of one arrayList to another arrayList in java ? both gives the same hashCode pls check below code

public static void main(String[] args) {
    ArrayList<String> c1= new ArrayList<String>();
    c1.add("Red");
    c1.add("Green");
    c1.add("Black");
    c1.add("White");
    c1.add("Pink");

    System.out.println("Original array list: " + c1);
    ArrayList<String> newc1 = new ArrayList<String>();

    newc1 = (ArrayList<String>) c1.clone();
    
    System.out.println("Cloned array list: " + newc1);
    
    ArrayList<String> c2 = new ArrayList<String>();
    c2.addAll(c1);
    
         
    System.out.println(c1.hashCode());
    System.out.println(newc1.hashCode());
    System.out.println(c2.hashCode());
    
 
}

what is the difference between clone method or copy of one arrayList to another arrayList in java? both gives the same hashCode pls check below code.

clone() is the function of the Obejct class, which is a kind of shallow copy, which means that it just copys the address of the object.

hashcode() of a list depends on the elements of the list, so if these list contains the same elements, they will have the same result value of hashcode(), unless you overwrite hashcode() by yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM