Skip to content

Commit

Permalink
8315850: Improve AbstractMap anonymous Iterator classes
Browse files Browse the repository at this point in the history
Reviewed-by: liach, smarks
  • Loading branch information
minborg committed Oct 12, 2023
1 parent 424de29 commit d95b548
Showing 1 changed file with 20 additions and 32 deletions.
52 changes: 20 additions & 32 deletions src/java.base/share/classes/java/util/AbstractMap.java
Original file line number Diff line number Diff line change
Expand Up @@ -350,23 +350,9 @@ public void clear() {
public Set<K> keySet() {
Set<K> ks = keySet;
if (ks == null) {
ks = new AbstractSet<K>() {
ks = new AbstractSet<>() {
public Iterator<K> iterator() {
return new Iterator<K>() {
private Iterator<Entry<K,V>> i = entrySet().iterator();

public boolean hasNext() {
return i.hasNext();
}

public K next() {
return i.next().getKey();
}

public void remove() {
i.remove();
}
};
return new KeyIterator();
}

public int size() {
Expand Down Expand Up @@ -409,23 +395,9 @@ public boolean contains(Object k) {
public Collection<V> values() {
Collection<V> vals = values;
if (vals == null) {
vals = new AbstractCollection<V>() {
vals = new AbstractCollection<>() {
public Iterator<V> iterator() {
return new Iterator<V>() {
private Iterator<Entry<K,V>> i = entrySet().iterator();

public boolean hasNext() {
return i.hasNext();
}

public V next() {
return i.next().getValue();
}

public void remove() {
i.remove();
}
};
return new ValueIterator();
}

public int size() {
Expand Down Expand Up @@ -924,4 +896,20 @@ public String toString() {
public <T> T[] toArray(T[] a) { return view().toArray(a); }
public String toString() { return view().toString(); }
}

// Iterator implementations.

final class KeyIterator implements Iterator<K> {
private final Iterator<Entry<K,V>> i = entrySet().iterator();
public boolean hasNext() { return i.hasNext(); }
public void remove() { i.remove(); }
public K next() { return i.next().getKey(); }
}

final class ValueIterator implements Iterator<V> {
private final Iterator<Entry<K,V>> i = entrySet().iterator();
public boolean hasNext() { return i.hasNext(); }
public void remove() { i.remove(); }
public V next() { return i.next().getValue(); }
}
}

1 comment on commit d95b548

@openjdk-notifier
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.