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 ) ()