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

Last change on this file since 7083 was 6792, checked in by Don-vip, 10 years ago

Sonar - fix various issues

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