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

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

為什么Object.equals(Object o)在Java中需要Object.hashCode?

為什么Object.equals(Object o)在Java中需要Object.hashCode?

慕哥9229398 2021-04-12 14:54:57
我有一個類型的對象列表,Person我想使用流擺脫具有相同名稱的元素。我在互聯網上發現了使用Wrapper類的建議,到目前為止,我的代碼看起來像這樣:List<Person> people = Arrays.asList(new Person("Kowalski"),                                    new Person("Nowak"),                                    new Person("Big"),                                    new Person("Kowalski"));List<Person> distPeople = people.stream()        .map(Wrapper::new)        .distinct()        .map(Wrapper::unwrap)        .collect(Collectors.toList());在文檔中,據說 distinct()返回由該流的不同元素組成的流(根據Object.equals(Object))。那樣的實現是Wrapper行不通的(我用兩個Kowalski得到了相同的流):public class Wrapper{    private final Person person;    Wrapper(Person p)    {        person = p;    }    public Person unwrap()    {        return person;    }    public boolean equals(Object other)    {        if(other instanceof Wrapper)            return ((Wrapper) other).person.getName().equals(person.getName());        else            return false;    }}Wrapper添加以下代碼后,類的實現工作即可:@Overridepublic int hashCode(){    return person.getName().hashCode();}覆蓋后有人可以解釋為什么hashCode()在Wrapper類distinct()的作品?
查看完整描述

3 回答

?
一只名叫tom的貓

TA貢獻1906條經驗 獲得超3個贊

答案就在全班DistinctOps。該方法makeRef用于返回ReferencePipeline包含不同元素的實例。此方法LinkedHashSet用于執行reduce操作以獲得不同的元素。請注意,它從中LinkedHashSet擴展用于存儲元素?,F在序的正常工作,你應該提供實現其遵循的正確合同和與therfore,需要您提供一個實現,使正常工作。HashSetHashMapHashMaphashCode()hashCode()equals()hasCode()Stream#distinct()

查看完整回答
反對 回復 2021-04-28
  • 3 回答
  • 0 關注
  • 222 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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