1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.functor.generator;
18
19 import org.apache.commons.functor.UnaryPredicate;
20 import org.apache.commons.functor.UnaryProcedure;
21
22
23
24
25
26
27
28 public class WhileGenerate<E> extends BaseGenerator<E> {
29 private final UnaryPredicate<? super E> test;
30
31
32
33
34
35
36 public WhileGenerate(UnaryPredicate<? super E> test, Generator<? extends E> wrapped) {
37 super(wrapped);
38 if (wrapped == null) {
39 throw new IllegalArgumentException("Generator argument was null");
40 }
41 if (test == null) {
42 throw new IllegalArgumentException("UnaryPredicate argument was null");
43 }
44 this.test = test;
45 }
46
47
48
49
50 public void run(final UnaryProcedure<? super E> proc) {
51 getWrappedGenerator().run(new UnaryProcedure<E>() {
52 public void run(E obj) {
53 if (!test.test(obj)) {
54 getWrappedGenerator().stop();
55 } else {
56 proc.run(obj);
57 }
58 }
59 });
60 }
61
62
63
64
65 @SuppressWarnings("unchecked")
66 @Override
67 protected Generator<? extends E> getWrappedGenerator() {
68 return (Generator<? extends E>) super.getWrappedGenerator();
69 }
70
71
72
73
74 public boolean equals(Object obj) {
75 if (obj == this) {
76 return true;
77 }
78 if (!(obj instanceof WhileGenerate<?>)) {
79 return false;
80 }
81 WhileGenerate<?> other = (WhileGenerate<?>) obj;
82 return other.getWrappedGenerator().equals(getWrappedGenerator()) && other.test.equals(test);
83 }
84
85
86
87
88 public int hashCode() {
89 int result = "WhileGenerate".hashCode();
90 result <<= 2;
91 Generator<?> gen = getWrappedGenerator();
92 result ^= gen == null ? 0 : gen.hashCode();
93 result <<= 2;
94 result ^= test == null ? 0 : test.hashCode();
95 return result;
96 }
97 }