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
27
28
29
30
31
32
33
34
35
36
37 public final class IsElementOf<L, R> implements BinaryPredicate<L, R>, Serializable {
38
39
40
41
42
43
44 private static final long serialVersionUID = -7639051806015321070L;
45 private static final IsElementOf<Object, Object> INSTANCE = new IsElementOf<Object, Object>();
46
47
48
49
50
51
52 public IsElementOf() {
53 }
54
55
56
57
58
59
60 public boolean test(L obj, R col) {
61 if (col instanceof Collection<?>) {
62 return testCollection(obj, (Collection<?>) col);
63 }
64 if (null != col && col.getClass().isArray()) {
65 return testArray(obj, col);
66 }
67 if (null == col) {
68 throw new IllegalArgumentException("Right side argument must not be null.");
69 }
70 throw new IllegalArgumentException("Expected Collection or Array, found " + col.getClass());
71 }
72
73
74
75
76 public boolean equals(Object obj) {
77 return (obj instanceof IsElementOf<?, ?>);
78 }
79
80
81
82
83 public int hashCode() {
84 return "IsElementOf".hashCode();
85 }
86
87
88
89
90 public String toString() {
91 return "IsElementOf";
92 }
93
94
95
96
97
98
99
100 private boolean testCollection(Object obj, Collection<?> col) {
101 return col.contains(obj);
102 }
103
104
105
106
107
108
109
110 private boolean testArray(Object obj, Object array) {
111 for (int i = 0, m = Array.getLength(array); i < m; i++) {
112 Object value = Array.get(array, i);
113 if (obj == value) {
114 return true;
115 }
116 if (obj != null && obj.equals(value)) {
117 return true;
118 }
119 }
120 return false;
121 }
122
123
124
125
126
127
128
129 public static IsElementOf<Object, Object> instance() {
130 return INSTANCE;
131 }
132
133
134
135
136
137
138 public static <A> UnaryPredicate<A> instance(Object obj) {
139 if (null == obj) {
140 throw new NullPointerException("Argument must not be null");
141 } else if (obj instanceof Collection<?>) {
142 return new RightBoundPredicate<A>(new IsElementOf<A, Object>(), obj);
143 } else if (obj.getClass().isArray()) {
144 return new RightBoundPredicate<A>(new IsElementOf<A, Object>(), obj);
145 } else {
146 throw new IllegalArgumentException("Expected Collection or Array, found " + obj.getClass());
147 }
148 }
149
150 }