首页 > 编程知识 正文

(java 迭代器 entryset,流VS。 Map的entrySet中的迭代器-Java 8)

时间:2023-05-06 17:18:43 阅读:123490 作者:4561

To my understanding,thefollowingcodeshouldhaveprinttrue,sincebothstreamanditeratorarepointingtothefirstelement。

However,wheniranthefollowingcodeitisprintingfalse :

final HashMap map=new HashMap (;

map.put(a )、b );

finalsetset=collections.unmodifiablemap (map ).entrySet );

Map.Entry entry1=set.iterator ().next );

Map.Entry entry2=set.stream ().findFirst ).get );

watcouldbethereasonforthisdifferentbehavior?

bothentriesarereferringtothesamelogicalentryofyourmap (whosekeyis ' a ' andvalueis ' b ' ).However,they are not the same insame

ifyoudigdeepenoughintheimplementationofcollections.unmodifiablemap (map )。 you ' llseethatiteratingovertheentrysetofthemapreturnedbycollections.unmodifiablemap (map ) returnsanewmap.entrywhichwraprap

公共地图. entry next (

returnnewunmodifiableentry (I.next );

}

I ' massuminganewinstancemap.entryinstanceisalsocreatedwhenyoucallset.stream (.findfirst ).get ),sothetwomethood

even if you ' llcallthesamethodtwiceyou ' llgetdifferenceinstances,I.e.thefollowingcodewillalsoprintfalse 3360

Map.Entry entry1=set.iterator ().next );

Map.Entry entry2=set.iterator ().next );

On the other hand,ifyouobtaintheentrydirectlyfromtheoriginalhashmap,you will get true:

Map.Entry entry1=map.entrySet ().iterator ).next );

map.entry entry2=map.entryset (.stream ).findFirst ).get );

ifthiscasetheentryisnotwrappedbyanewinstance,sobothentryset(.iterator ).next ) (and entrySet ).stream ) ()

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。