java中列表深复制的三种方法

时间:2024-03-07 22:10:43
有两种方式:

1.循环

循环第一个list,然后每循环一次,就给新的list赋值

List<String> oneList = new ArrayList<String>();
List<String> twoList = new ArrayList<String>();
oneList.add("1");
oneList.add("2");
oneList.add("3");

for(String str : oneList){
twoList.add(str);
}


for(String str : twoList){
System.out.println(str);
}

结果:

1
2
3


2.arrayList的addAll()方法

List<String> oneList = new ArrayList<String>();
oneList.add("1");
oneList.add("2");
oneList.add("3");

for(String str : oneList){
System.out.println("one:"+str);
}

List<String> twoList = new ArrayList<String>();
twoList.add("4");
twoList.addAll(oneList);
for(String str : twoList){
System.out.println("two:"+str);
}
3、构造器
public class T1 {
    private static ArrayList<String> dateType = new ArrayList<String>(){{
        this.add("2020-01");
        this.add("2020-02");
        this.add("2020-03");
    }};

    public static void main(String[] args) {
        final ArrayList<String> list = new ArrayList<String>() {{
            this.add("2020-01");
            this.add("2020-02");
        }};

        System.out.println(dateType);
        final ArrayList<String> strings = new ArrayList<>(dateType);

        strings.removeAll(list);
        System.out.println("strings:"+strings);
        System.out.println("后dateType:"+dateType);
    }
}

结果:

one:1
one:2
one:3
two:4
two:1
two:2
two:3