gpt4 book ai didi

Java arraylist 复制 - 克隆?

转载 作者:行者123 更新时间:2023-11-29 03:32:22 26 4
gpt4 key购买 nike

我正在尝试复制 ArrayList , 但它似乎只是引用它而不是真正复制它。

我的代码:

List<Column> columns = columnData(referencedField.table);
List<Field> newPath = new ArrayList<>(startPath);
System.out.println("Equals? " + (newPath.equals(startPath)));

startPath是一个 ArrayList<Field>被传递到函数中。

领域:

public class Field 
{
public String table;
public String column;

public Field(final String table, final String column) {
this.table = table;
this.column = column;
}

@Override
public String toString() {
return "(" + table + ", " + column + ")";
}

@Override
public int hashCode() {
int hash = 3;
hash = 67 * hash + Objects.hashCode(this.table);
hash = 67 * hash + Objects.hashCode(this.column);
return hash;
}

@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Field other = (Field) obj;
if (!Objects.equals(this.table, other.table)) {
return false;
}
if (!Objects.equals(this.column, other.column)) {
return false;
}
return true;
}
}

现在我已经阅读了有关克隆它的内容,但我没有这方面的经验。我实际上想知道克隆是否真的会创建一个新对象列表,这样它们就不再相等了,因为对于相同的内容,元素将是相等的。

换句话说,我想要的是:确保 startPathnewPath不相等,因此不相互引用,因为我使用的列表是一个递归函数,应该将列表添加到 map 中。

最佳答案

你需要做一个深拷贝。

List<Field> newPath = new ArrayList<>();
for(Field field: startPath){
newPath.add(field.clone());
}

关于Java arraylist 复制 - 克隆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17565911/

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