java - not able to understand entrySet() method -
we can use entryset() method iterate on hashmap key-value pairs stored in node[] table field .
hahmap<k,v> hashmap = new hashmap<>() ; public set<map.entry<k,v>> entryset() { set<map.entry<k,v>> es; return (es = entryset) == null ? (entryset = new entryset()) : es; }
when use in for-each loop :
for ( map.entry<k,v> entry : hashmap.entryset () ) { ... // entry object of return type map.entry , object type node . // got object type calling entry.getclass() , no other inner class other node implements map.entry . ; }
these objects stored in set . code links them field table has key-value pairs .
for example : in tostring() method when iterable using iterator() method , , call next() method on iterable call goes nextnode() of hashiterator class object returned linked table field of hashmap class . happens here ? please .
you seem lack understanding of view is. view has no stored data, fulfills interface delegating actual data object.
a simple example list view created via collections.unmodifiablelist(…)
not contain data, delegates method calls original list, excluding modification methods, of course.
the entry set fulfills set
interface delegating underlying map. notably, returning iterator
, methods build upon this, few others overridden performance, e.g. size()
delegates directly map’s size()
. if appears if entry set contains something, is, because iterator reports during traversal.
the hashmap
’s entry set iterator iterates on internal array of entries, key set iterator , value collection iterator. difference between them object return in next()
method, entry set iterator returns entry, other 2 extract key resp. value of entry. that’s why these iterator override single method.
note interaction can seen other way round. when implement map
extending abstractmap
, entryset()
only method need implement, other map methods implemented via delegation entry set. might override of them performance, though. question, contains data, moot, both, map
, entry set
views same underlying data.
maybe following example helps:
string[][] pairs={ {"foo","bar"}, {"hello","world"} }; map<string,string> map = new abstractmap<string, string>() { public set<map.entry<string, string>> entryset() { return new abstractset<entry<string, string>>() { public iterator<map.entry<string, string>> iterator() { return arrays.stream(pairs) .<entry<string,string>>map(p -> new simpleimmutableentry<>(p[0],p[1])) .iterator(); } public int size() { return pairs.length; } }; } }; system.out.println(map.get("foo")); system.out.println(map.containskey("hello")); system.out.println(map.containsvalue("world")); map.foreach((k,v) -> system.out.println(k+" -> "+v)); system.out.println(map);
it creates immutable map never put into. still, reports intended contents through map
methods, because entry set iterator reports content.
Comments
Post a Comment