我有個疑問,我想檢查一下java中的TreeSet是否真的爲它的clone()使用了淺拷貝,但是如果我從父樹set中移除了一個元素,那麼它不會反映在它的克隆的treeset對象中。Treeset的clone()的證明在java中創建淺拷貝?
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<Name> nameTreeSet = new TreeSet<>();
nameTreeSet.add(new Name("Compiere"));
nameTreeSet.add(new Name("Aristotle"));
nameTreeSet.add(new Name("CompierE"));
nameTreeSet.add(new Name("COmpiere"));
nameTreeSet.add(new Name("ArisTotle"));
nameTreeSet.add(new Name("arisTotle"));
nameTreeSet.add(new Name("aristotle"));
System.out.println(nameTreeSet);
TreeSet<Name> cloneNameTreeSet = (TreeSet<Name>) nameTreeSet.clone();
System.out.println(nameTreeSet);
Iterator<Name> itr = nameTreeSet.iterator();
/*while (itr.hasNext()) {
if (itr.next().getName().equals("aristotle"))
itr.remove();
}*/
for(Name name: nameTreeSet) {
if(name.getName().equals("aristotle"))
nameTreeSet.remove(name);
}
System.out.println(nameTreeSet);
System.out.println(cloneNameTreeSet);
}
}
/*
*Name class which is used in my treeset to store its objects
*/
public class Name implements Cloneable, Comparable<Name>, Comparator<Name> {
@Override
public String toString() {
return "Name [name=" + name + "]";
}
private String name;
public Name(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Name other = (Name) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public int compare(Name name1, Name name2) {
return name1.name.compareTo(name2.name);
}
@Override
public int compareTo(Name name) {
return (this.name).compareTo(name.name);
}
}
請給我建議,更正非常感謝:) – Arafath
爲什麼你會期望一個元素被從克隆的實例中刪除,如果你從原來的刪除它? 'clone()'創建一個單獨的實例,具有單獨的狀態,因此原始中的更改不會反映在克隆中(反之亦然) –
淺拷貝仍然是副本:您可以更改一個,而不會影響另一個。 – khelwood