DynamicSet: Return Iterable for entries instead of Iterator

This makes iterating over the entries with a for loop easier.

Change-Id: I55f7b4efe4ef2ba294116382409ffafd464925a6
Signed-off-by: Edwin Kempin <ekempin@google.com>
This commit is contained in:
Edwin Kempin 2018-09-03 14:30:04 +02:00
parent d7c995855f
commit 5b1ddd2c78
2 changed files with 34 additions and 29 deletions

View File

@ -168,7 +168,7 @@ public class DynamicSet<T> implements Iterable<T> {
@Override
public Iterator<T> iterator() {
Iterator<Entry<T>> entryIterator = entryIterator();
Iterator<Entry<T>> entryIterator = entries().iterator();
return new Iterator<T>() {
@Override
public boolean hasNext() {
@ -183,39 +183,44 @@ public class DynamicSet<T> implements Iterable<T> {
};
}
public Iterator<Entry<T>> entryIterator() {
public Iterable<Entry<T>> entries() {
final Iterator<AtomicReference<NamedProvider<T>>> itr = items.iterator();
return new Iterator<Entry<T>>() {
private Entry<T> next;
return new Iterable<Entry<T>>() {
@Override
public boolean hasNext() {
while (next == null && itr.hasNext()) {
NamedProvider<T> p = itr.next().get();
if (p != null) {
try {
next = new Entry<>(p.pluginName, p.impl);
} catch (RuntimeException e) {
// TODO Log failed member of DynamicSet.
public Iterator<Entry<T>> iterator() {
return new Iterator<Entry<T>>() {
private Entry<T> next;
@Override
public boolean hasNext() {
while (next == null && itr.hasNext()) {
NamedProvider<T> p = itr.next().get();
if (p != null) {
try {
next = new Entry<>(p.pluginName, p.impl);
} catch (RuntimeException e) {
// TODO Log failed member of DynamicSet.
}
}
}
return next != null;
}
}
return next != null;
}
@Override
public Entry<T> next() {
if (hasNext()) {
Entry<T> result = next;
next = null;
return result;
}
throw new NoSuchElementException();
}
@Override
public Entry<T> next() {
if (hasNext()) {
Entry<T> result = next;
next = null;
return result;
}
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}

View File

@ -123,7 +123,7 @@ public class DynamicSetTest {
ds.add("bar", 2);
ds.add("bar", 3);
Iterator<DynamicSet.Entry<Integer>> entryIterator = ds.entryIterator();
Iterator<DynamicSet.Entry<Integer>> entryIterator = ds.entries().iterator();
DynamicSet.Entry<Integer> next = entryIterator.next();
assertThat(next.getPluginName()).isEqualTo("foo");
assertThat(next.getProvider().get()).isEqualTo(1);