1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.functor.core.composite;
18
19 import java.io.Serializable;
20
21 import org.apache.commons.functor.UnaryPredicate;
22 import org.apache.commons.functor.UnaryProcedure;
23 import org.apache.commons.functor.core.NoOp;
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44 public final class ConditionalUnaryProcedure<A> implements UnaryProcedure<A>, Serializable {
45
46
47
48 private static final long serialVersionUID = -895833369740247391L;
49
50
51 private static final int HASH_SHIFT = 4;
52
53
54 private final UnaryPredicate<? super A> ifPred;
55 private final UnaryProcedure<? super A> thenProc;
56 private final UnaryProcedure<? super A> elseProc;
57
58
59
60
61
62
63
64
65 public ConditionalUnaryProcedure(UnaryPredicate<? super A> ifPred, UnaryProcedure<? super A> thenProc) {
66 this(ifPred, thenProc, NoOp.instance());
67 }
68
69
70
71
72
73
74
75 public ConditionalUnaryProcedure(UnaryPredicate<? super A> ifPred,
76 UnaryProcedure<? super A> thenProc,
77 UnaryProcedure<? super A> elseProc) {
78 if (ifPred == null) {
79 throw new IllegalArgumentException("UnaryPredicate argument was null");
80 }
81 this.ifPred = ifPred;
82 if (thenProc == null || elseProc == null) {
83 throw new IllegalArgumentException("One or more UnaryProcedure arguments was null");
84 }
85 this.thenProc = thenProc;
86 this.elseProc = elseProc;
87 }
88
89
90
91
92
93
94 public void run(A obj) {
95 if (ifPred.test(obj)) {
96 thenProc.run(obj);
97 } else {
98 elseProc.run(obj);
99 }
100 }
101
102
103
104
105 public boolean equals(Object that) {
106 return that == this || (that instanceof ConditionalUnaryProcedure<?>
107 && equals((ConditionalUnaryProcedure<?>) that));
108 }
109
110
111
112
113
114
115 public boolean equals(ConditionalUnaryProcedure<?> that) {
116 return null != that
117 && (null == ifPred ? null == that.ifPred : ifPred.equals(that.ifPred))
118 && (null == thenProc ? null == that.thenProc : thenProc.equals(that.thenProc))
119 && (null == elseProc ? null == that.elseProc : elseProc.equals(that.elseProc));
120 }
121
122
123
124
125 public int hashCode() {
126 int hash = "ConditionalUnaryProcedure".hashCode();
127 if (null != ifPred) {
128 hash <<= HASH_SHIFT;
129 hash ^= ifPred.hashCode();
130 }
131 if (null != thenProc) {
132 hash <<= HASH_SHIFT;
133 hash ^= thenProc.hashCode();
134 }
135 if (null != elseProc) {
136 hash <<= HASH_SHIFT;
137 hash ^= elseProc.hashCode();
138 }
139 return hash;
140 }
141
142
143
144
145 public String toString() {
146 return "ConditionalUnaryProcedure<" + ifPred + "?" + thenProc + ":" + elseProc + ">";
147 }
148
149 }