为了账号安全,请及时绑定邮箱和手机立即绑定

distinct() 方法不为 HashSet 元素流返回不同的元素

distinct() 方法不为 HashSet 元素流返回不同的元素

凤凰求蛊 2022-08-17 10:57:23
假设我有员工类,具有正确覆盖的等于和哈希码方法。public class Employee {private int eno;private String firstName;private String lastName;@Overridepublic int hashCode() {    System.out.println("hashcode called");    final int prime = 31;    int result = 1;    result = prime * result + eno;    result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());    result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());    return result;}@Overridepublic boolean equals(Object obj) {    System.out.println("equals called");    if (this == obj)        return true;    if (obj == null)        return false;    if (getClass() != obj.getClass())        return false;    Employee other = (Employee) obj;    if (eno != other.eno)        return false;    if (firstName == null) {        if (other.firstName != null)            return false;    } else if (!firstName.equals(other.firstName))        return false;    if (lastName == null) {        if (other.lastName != null)            return false;    } else if (!lastName.equals(other.lastName))        return false;    return true;}}测试类如下class Test {    public static void main(String[] args) {        Employee e1 = new Employee(1, "Karan", "Mehara");        Employee e2 = new Employee(2, "Rajesh", "Shukla");        Set<Employee> emps= new HashSet<>();        emps.add(e1);        emps.add(e2);        System.out.println(emps);        // No such requirement just for testing purpose modifying         e2.setEno(1);        e2.setFirstName("Karan");        e2.setLastName("Mehara");        System.out.println(emps);        emps.stream().distinct().forEach(System.out::println);    }员工 [eno=1, 名字=Karan, lastName=Mehara]员工 [eno=1, 名字=Karan, lastName=Mehara]为什么 distinct() 方法返回重复的元素??根据雇员类的 equals() 和 hashcode() 方法,这两个对象是相同的。我观察到,当我调用 distinct() method equals() 和 hashcode() 方法时,它不会获得对 Set 实现流的调用,但它会获得对 List 实现流的调用。根据JavaDoc的说法,distinct()返回由该流的不同元素(根据Object.equals(Object))组成的流。
查看完整描述

1 回答

?
桃花长相依

TA贡献1860条经验 获得超8个赞

定义为“不包含重复元素的集合”。因此,a 的 -方法最有可能被实现为什么都不做,因为它已经证明值是唯一的。SetStreamdistinctSet

Javadoc 中明确提到了您所做的操作:

注意:如果将可变对象用作集合元素,则必须格外小心。如果对象的值的更改方式会影响相等比较,而对象是集合中的元素,则不会指定集合的行为。此禁止的一个特殊情况是,不允许集合将自身作为元素包含。


查看完整回答
反对 回复 2022-08-17
  • 1 回答
  • 0 关注
  • 83 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信