gpt4 book ai didi

java - TreeSet 违反了 Set 契约?

转载 作者:行者123 更新时间:2023-12-02 09:07:04 24 4
gpt4 key购买 nike

我试图回答this在论坛中提出问题,我发现尽管重写了 Employee 类中的 equals 方法,我仍然能够向 TreeSet 添加重复元素>.

TreeSet.add(E) 的 Javadoc方法说

Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if the set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.

这本质上意味着不会将 2 个 equals 对象插入到 TreeSet 中,并且相等性仅由所包含对象的 equals() 方法确定。

但是,下面的代码将 2 个元素添加到 Set 中,即使它们相等

public class Employee implements Comparable<Employee> {

String employeeName;
int employeeId;

public Employee(String name, int id) {
this.employeeName = name;
this.employeeId = id;
}

public int compareTo(Employee emp) {
//return this.employeeName.compareTo(emp.employeeName);
return (this.employeeId - emp.employeeId);
}

@Override
public String toString() {
return ("Name is: " + employeeName + " Emp id is: " + employeeId);
}

@Override
public boolean equals(Object emp) {
if(emp instanceof Employee &&((Employee)emp).employeeName.equals(this.employeeName)){
return true;
}
return false;
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Set<Employee> set = new TreeSet<Employee>();
Employee e1 = new Employee("A", 1);
Employee e2 = new Employee("A", 2);
System.out.println(e1.equals(e2));
set.add(e1);
set.add(e2);
System.out.println(set);
}

}

这是输出

true
[Name is: A Emp id is: 1, Name is: A Emp id is: 2]

为什么 TreeSet 允许多个元素,即使它们相等?

现在我像这样更改了 EmployeecompareTo 方法

public int compareTo(Employee emp) {
return this.employeeName.compareTo(emp.employeeName);
}

输出是

true
[Name is: A Emp id is: 1]

重写 compareToTreeSet 如何正常工作?

最佳答案

TreeSet 的 javadoc 还说:

Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

我同意 add() 的 javadoc 可以更清楚地表明 equals() 并未实际使用,并且重新声明或链接到此警告,不过.

关于java - TreeSet 违反了 Set 契约?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17609419/

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