gpt4 book ai didi

java - 使用比较器时从 TreeSet 丢失的数据

转载 作者:搜寻专家 更新时间:2023-11-01 01:15:46 26 4
gpt4 key购买 nike

我有以下代码,可以根据他们的经验对员工 进行排序。

我要添加 2 名具有不同姓名 和相同经验 的员工。我预计 set 最后会有 2 名员工,但我只得到一名员工。

我还覆盖了 equalshashcode,谁能告诉我为什么我在集合中只有一名员工。

测试类

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.junit.Test;

public class SetWithComparator {


@Test
public void testComparatorWithSet() {

Comparator<Employee> comparator =
(emp1, emp2) -> emp1.getYearOFExp().compareTo(emp2.getYearOFExp());

Set<Employee> empSet = new TreeSet<>(comparator);

Employee e1 = new Employee();
e1.setName("Employee-1");
e1.setYearOFExp(12f);

Employee e2 = new Employee();
e2.setName("Employee-2");
e2.setYearOFExp(12f);

empSet.add(e1);
empSet.add(e2);

}

}

模型类

class Employee {


private String name;
private Float yearOFExp;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Float getYearOFExp() {
return yearOFExp;
}

public void setYearOFExp(Float yearOFExp) {
this.yearOFExp = yearOFExp;
}

@Override
public boolean equals(Object obj) {

if (obj instanceof Employee) {

Employee e = (Employee) obj;
return new EqualsBuilder().append(name, e.getName()).isEquals();
} else {
return false;
}

}

@Override
public int hashCode() {
return new HashCodeBuilder().append(name).toHashCode();
}

}

最佳答案

因为比较器和你的equals方法不一致。请查看 Comparator 的文档.

The ordering imposed by a comparator c on a set of elements S is said to be consistent with equals if and only if c.compare(e1, e2)==0 has the same boolean value as e1.equals(e2) for every e1 and e2 in S.

Caution should be exercised when using a comparator capable of imposing an ordering inconsistent with equals to order a sorted set (or sorted map). Suppose a sorted set (or sorted map) with an explicit comparator c is used with elements (or keys) drawn from a set S. If the ordering imposed by c on S is inconsistent with equals, the sorted set (or sorted map) will behave "strangely." In particular the sorted set (or sorted map) will violate the general contract for set (or map), which is defined in terms of equals.

您所经历的确切行为在 Comparable 的文档中有所暗示(虽然你使用比较器):

For example, if one adds two keys a and b such that (!a.equals(b) && a.compareTo(b) == 0) to a sorted set that does not use an explicit comparator, the second add operation returns false (and the size of the sorted set does not increase) because a and b are equivalent from the sorted set's perspective.

在你的例子中:comparator.compare(e1, e2)0e1.equals(e2)false

关于java - 使用比较器时从 TreeSet 丢失的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41628658/

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