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.UnaryFunction;
22 import org.apache.commons.functor.UnaryPredicate;
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44 public final class ConditionalUnaryFunction<A, T> implements UnaryFunction<A, T>, Serializable {
45
46
47
48 private static final long serialVersionUID = -8152490481969255068L;
49
50
51 private static final int HASH_SHIFT = 4;
52
53
54 private final UnaryPredicate<? super A> ifPred;
55 private final UnaryFunction<? super A, ? extends T> thenFunc;
56 private final UnaryFunction<? super A, ? extends T> elseFunc;
57
58
59
60
61
62
63
64
65
66 public ConditionalUnaryFunction(UnaryPredicate<? super A> ifPred, UnaryFunction<? super A, ? extends T> thenFunc,
67 UnaryFunction<? super A, ? extends T> elseFunc) {
68 if (ifPred == null) {
69 throw new IllegalArgumentException("UnaryPredicate argument was null");
70 }
71 this.ifPred = ifPred;
72 if (thenFunc == null || elseFunc == null) {
73 throw new IllegalArgumentException("One or more UnaryFunction arguments was null");
74 }
75 this.thenFunc = thenFunc;
76 this.elseFunc = elseFunc;
77 }
78
79
80
81
82
83
84 public T evaluate(A obj) {
85 if (ifPred.test(obj)) {
86 return thenFunc.evaluate(obj);
87 } else {
88 return elseFunc.evaluate(obj);
89 }
90 }
91
92
93
94
95 public boolean equals(Object that) {
96 return that == this || (that instanceof ConditionalUnaryFunction<?, ?>
97 && equals((ConditionalUnaryFunction<?, ?>) that));
98 }
99
100
101
102
103
104
105 public boolean equals(ConditionalUnaryFunction<?, ?> that) {
106 return null != that
107 && (null == ifPred ? null == that.ifPred : ifPred.equals(that.ifPred))
108 && (null == thenFunc ? null == that.thenFunc : thenFunc.equals(that.thenFunc))
109 && (null == elseFunc ? null == that.elseFunc : elseFunc.equals(that.elseFunc));
110 }
111
112
113
114
115 public int hashCode() {
116 int hash = "ConditionalUnaryFunction".hashCode();
117 if (null != ifPred) {
118 hash <<= HASH_SHIFT;
119 hash ^= ifPred.hashCode();
120 }
121 if (null != thenFunc) {
122 hash <<= HASH_SHIFT;
123 hash ^= thenFunc.hashCode();
124 }
125 if (null != elseFunc) {
126 hash <<= HASH_SHIFT;
127 hash ^= elseFunc.hashCode();
128 }
129 return hash;
130 }
131
132
133
134
135 public String toString() {
136 return "ConditionalUnaryFunction<" + ifPred + "?" + thenFunc + ":" + elseFunc + ">";
137 }
138
139 }