亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 141 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號