source: josm/trunk/src/org/openstreetmap/josm/tools/SubclassFilteredCollection.java@ 10316

Last change on this file since 10316 was 9854, checked in by Don-vip, 8 years ago

sonar - squid:S2272 - "Iterator.next()" methods should throw "NoSuchElementException" + javadoc/code style

  • Property svn:eol-style set to native
File size: 2.8 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import java.util.AbstractCollection;
5import java.util.Collection;
6import java.util.Iterator;
7import java.util.NoSuchElementException;
8
9/**
10 * Filtered view of a collection.
11 * (read-only collection, but elements can be changed, of course)
12 * Lets you iterate through those elements of a given collection that satisfy a
13 * certain condition (imposed by a predicate).
14 * @param <S> element type of the underlying collection
15 * @param <T> element type of filtered collection (and subclass of S). The predicate
16 * must accept only objects of type T.
17 * @since 3147
18 */
19public class SubclassFilteredCollection<S, T extends S> extends AbstractCollection<T> {
20
21 private final Collection<? extends S> collection;
22 private final Predicate<? super S> predicate;
23 private int size = -1;
24
25 private class FilterIterator implements Iterator<T> {
26
27 private final Iterator<? extends S> iterator;
28 private S current;
29
30 FilterIterator(Iterator<? extends S> iterator) {
31 this.iterator = iterator;
32 }
33
34 private void findNext() {
35 if (current == null) {
36 while (iterator.hasNext()) {
37 current = iterator.next();
38 if (predicate.evaluate(current))
39 return;
40 }
41 current = null;
42 }
43 }
44
45 @Override
46 public boolean hasNext() {
47 findNext();
48 return current != null;
49 }
50
51 @SuppressWarnings("unchecked")
52 @Override
53 public T next() {
54 if (!hasNext())
55 throw new NoSuchElementException();
56 S old = current;
57 current = null;
58 // we are save because predicate only accepts objects of type T
59 return (T) old;
60 }
61
62 @Override
63 public void remove() {
64 throw new UnsupportedOperationException();
65 }
66 }
67
68 /**
69 * Constructs a new {@code SubclassFilteredCollection}.
70 * @param collection The base collection to filter
71 * @param predicate The predicate to use as filter
72 */
73 public SubclassFilteredCollection(Collection<? extends S> collection, Predicate<? super S> predicate) {
74 this.collection = collection;
75 this.predicate = predicate;
76 }
77
78 @Override
79 public Iterator<T> iterator() {
80 return new FilterIterator(collection.iterator());
81 }
82
83 @Override
84 public int size() {
85 if (size == -1) {
86 size = 0;
87 Iterator<T> it = iterator();
88 while (it.hasNext()) {
89 size++;
90 it.next();
91 }
92 }
93 return size;
94 }
95
96 @Override
97 public boolean isEmpty() {
98 return !iterator().hasNext();
99 }
100}
Note: See TracBrowser for help on using the repository browser.