1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.functor.core.collection;
18
19 import java.io.Serializable;
20 import java.lang.reflect.Array;
21 import java.util.Collection;
22
23 import org.apache.commons.functor.BinaryPredicate;
24 import org.apache.commons.functor.UnaryPredicate;
25 import org.apache.commons.functor.adapter.RightBoundPredicate;
26 import org.apache.commons.lang3.Validate;
27
28
29
30
31
32
33
34
35
36
37
38 public final class IsElementOf<L, R> implements BinaryPredicate<L, R>, Serializable {
39
40
41
42
43
44
45 private static final long serialVersionUID = -7639051806015321070L;
46
47
48
49 private static final IsElementOf<Object, Object> INSTANCE = new IsElementOf<Object, Object>();
50
51
52
53
54
55
56 public IsElementOf() {
57 }
58
59
60
61
62
63
64 public boolean test(L obj, R col) {
65 Validate.notNull(col, "Right side argument must not be null.");
66 if (col instanceof Collection<?>) {
67 return testCollection(obj, (Collection<?>) col);
68 }
69 if (col.getClass().isArray()) {
70 return testArray(obj, col);
71 }
72 throw new IllegalArgumentException("Expected Collection or Array, found " + col.getClass());
73 }
74
75
76
77
78 @Override
79 public boolean equals(Object obj) {
80 return (obj instanceof IsElementOf<?, ?>);
81 }
82
83
84
85
86 @Override
87 public int hashCode() {
88 return "IsElementOf".hashCode();
89 }
90
91
92
93
94 @Override
95 public String toString() {
96 return "IsElementOf";
97 }
98
99
100
101
102
103
104
105 private boolean testCollection(Object obj, Collection<?> col) {
106 return col.contains(obj);
107 }
108
109
110
111
112
113
114
115 private boolean testArray(Object obj, Object array) {
116 for (int i = 0, m = Array.getLength(array); i < m; i++) {
117 Object value = Array.get(array, i);
118 if (obj == value) {
119 return true;
120 }
121 if (obj != null && obj.equals(value)) {
122 return true;
123 }
124 }
125 return false;
126 }
127
128
129
130
131
132
133
134 public static IsElementOf<Object, Object> instance() {
135 return INSTANCE;
136 }
137
138
139
140
141
142
143
144
145 public static <A> UnaryPredicate<A> instance(Object obj) {
146 if (null == obj) {
147 throw new NullPointerException("Argument must not be null");
148 } else if (obj instanceof Collection<?>) {
149 return new RightBoundPredicate<A>(new IsElementOf<A, Object>(), obj);
150 } else if (obj.getClass().isArray()) {
151 return new RightBoundPredicate<A>(new IsElementOf<A, Object>(), obj);
152 } else {
153 throw new IllegalArgumentException("Expected Collection or Array, found " + obj.getClass());
154 }
155 }
156
157 }