gpt4 book ai didi

java - 如何在不指向 Java 源列表中的对象的情况下复制 ArrayList?

转载 作者:行者123 更新时间:2023-12-01 17:41:58 24 4
gpt4 key购买 nike

我的问题是我想复制其中包含对象的 ArrayList。
之后,我想更改“复制列表”中的对象,而不更改源列表中的对象。

我已经尝试过:

ArrayList<..> copy = new ArrayList<..>(sourceList); 
Collections.copy(dest, src);

更具体的问题在这里:

ArrayList<Exon> regions1 = new ArrayList<>();
regions1.add(r1);
regions1.add(r2);
regions1.add(r3);
System.out.println("Reg 1");
for (Exon e : regions1) {
System.out.println(e.getStart());
}

ArrayList<Exon> copy = new ArrayList<>(regions1);
System.out.println("Copy");
for (Exon e : copy) {
e.setStart(2);
System.out.println(e.getStart());
}
System.out.println("Reg 1 - untouched");
for (Exon e : regions1) {
System.out.println(e.getStart());
}

我得到的输出是:

Reg 1
5
15
100
Copy
2
2
2
Reg 1
2
2
2

我想要的输出是:

Reg 1
5
15
100
Copy
2
2
2
Reg 1
5
15
100

最佳答案

您只需为 Exon 创建一个复制构造函数即可。然后在 foreach 中,您必须传递 new Exon 对象。(with start=2)

A copy constructor: That's helpful when we want to copy a complex object that has several fields, or when we want to make a deep copy of an existing object.

<小时/>

1- Create copy constructor for Exon

public class Exon {

private int start;

//Copy constructor
public Exon(Exon exon) {
this.start = exon.getStart();
}

//Main Constructor and Getters and Setters

}

2- Create a copy from main list

 List<Exon> CopyList = mainList.stream().map(exon -> {
Exon copyExon = new Exon();
copyExon.setStart(2);
return new Exon(copyExon);
}).collect(Collectors.toList());

我按如下方式编写了您的代码:

public static void main(String[] args) {

//Initialize
ArrayList<Exon> mainList = new ArrayList<>();
Exon r1 = new Exon();
r1.setStart(5);
Exon r2 = new Exon();
r2.setStart(10);
Exon r3 = new Exon();
r3.setStart(15);
mainList.add(r1);
mainList.add(r2);
mainList.add(r3);

//Print mainList
System.out.println("Reg 1");
for (Exon e : mainList) {
System.out.println(e.getStart());
}

//Copy the mainList (I changed your foreach)
List<Exon> copyList = mainList.stream().map(exon -> {

//Create New Exon
Exon copyExon = new Exon(exon);
copyExon.setStart(2);
return copyExon ;

}).collect(Collectors.toList());

//Print copyList
System.out.println("Copy");
for (Exon e : copyList) {
System.out.println(e.getStart());
}

//Print mainList
System.out.println("Reg 1 - untouched");
for (Exon e : mainList) {
System.out.println(e.getStart());
}
}

结果:

Reg 1
5
10
15
Copy
2
2
2
Reg 1 - untouched
5
10
15

This link可能对复制构造函数有用

关于java - 如何在不指向 Java 源列表中的对象的情况下复制 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59973154/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com