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.lang.reflect.Array;
20 import java.util.Collection;
21
22 import org.apache.commons.functor.Function;
23 import org.apache.commons.lang3.Validate;
24
25
26
27
28
29
30
31
32 public final class Size<A> implements Function<A, Integer> {
33
34
35
36
37 private static final Size<Object> INSTANCE = new Size<Object>();
38
39
40
41
42
43
44 public Size() { }
45
46
47
48
49 public Integer evaluate(Object obj) {
50 Validate.notNull(obj, "Argument must not be null");
51 if (obj instanceof Collection<?>) {
52 return evaluate((Collection<?>) obj);
53 }
54 if (obj instanceof String) {
55 return evaluate((String) obj);
56 }
57 if (obj.getClass().isArray()) {
58 return evaluateArray(obj);
59 }
60 throw new IllegalArgumentException("Expected Collection, String or Array, found " + obj);
61 }
62
63
64
65
66 @Override
67 public boolean equals(Object that) {
68 return that instanceof Size<?>;
69 }
70
71
72
73
74 @Override
75 public int hashCode() {
76 return "Size".hashCode();
77 }
78
79
80
81
82 @Override
83 public String toString() {
84 return "Size()";
85 }
86
87
88
89
90
91 public static Size<Object> instance() {
92 return INSTANCE;
93 }
94
95
96
97
98
99
100 private Integer evaluate(Collection<?> col) {
101 return Integer.valueOf(col.size());
102 }
103
104
105
106
107
108
109 private Integer evaluate(String str) {
110 return Integer.valueOf(str.length());
111 }
112
113
114
115
116
117
118 private Integer evaluateArray(Object array) {
119 return Integer.valueOf(Array.getLength(array));
120 }
121
122 }