Problem
I'm trying to understand how Sun implemented the entrySet, keySet, and HashMap class methods, but I come across code that doesn't make sense to me.
I understand conceptually that these methods return views directly related to the map.entry list in HashMap, and that they use their own iterators (referencing the central HashMap iterator) for most of their work. My problem is understanding how exactly these views are created in the first place (since they are not a copy, but something that sits on top of the top HashMap list).
Link
I look at the source code located on this site: http://developer.classpath.org/doc/java/util/HashMap-source.html
Here is one of the snippets that give me problems:
157: private transient Set<Map.Entry<K, V>> entries;
594: public Set<Map.Entry<K, V>> entrySet()
595: {
596: if (entries == null)
597: // Create an AbstractSet with custom implementations of those methods
598: // that can be overridden easily and efficiently.
599: entries = new AbstractSet<Map.Entry<K, V>>()
600: {
601: public int size()
602: {
603: return size;
604: }
605:
606: public Iterator<Map.Entry<K, V>> iterator()
607: {
608: // Cannot create the iterator directly, because of LinkedHashMap.
609: return HashMap.this.iterator(ENTRIES);
610: }
611:
612: public void clear()
613: {
614: HashMap.this.clear();
615: }
616:
617: public boolean contains(Object o)
618: {
619: return getEntry(o) != null;
620: }
621:
622: public boolean remove(Object o)
623: {
624: HashEntry<K, V> e = getEntry(o);
625: if (e != null)
626: {
627: HashMap.this.remove(e.key);
628: return true;
629: }
630: return false;
631: }
632: };
633: return entries;
634: }
Questions
On line 599, this code creates an instance of the AbstractSet class. How is this possible? I tried to recreate this myself, but I get the expected compilation errors.
I assume the public methods on lines 601, 606, 612, 617 and 622 are anonymous inner classes? I have never used this functionality before, so I'm sure it works, and the only examples that I find on the Internet are quite simplified (and mostly related to Swing). I have to assume that line 599 is directly related to an anonymous class, but I don't know how to do this.
I would really appreciate it if someone could explain this to me! Thanks!