Make a deep copy of the List in java and perform a deletion test

List<String> list = new ArrayList<>(); // The original List that needs to be copied

list.add("aaa");

list.add("bbb");

list.add("ccc");

List<String> listNew = new ArrayList<>();  // 新List

// Assign the value of the original List to the new List

CollectionUtils.mergeArrayIntoCollection(new Object[list.size()], listNew);

Collections.copy(listNew, list);

// Now delete one of the values ​​in the heart list, and you will find that the original list is not affected, for example:

List<String> list_remove= new ArrayList<>();  // 中间List

for (String s : listNew){

    if("aaa".equals(s)){

        list_remove.add(s);

    }

}

listNew.removeAll(list_remove);

System.out.println(listNew);    // [bbb, ccc]

System.out.println(list); // [aaa, bbb, ccc] The original list has not changed

Guess you like

Origin blog.csdn.net/dd2016124/article/details/132543021