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.UnaryFunction;
24
25
26
27
28
29
30
31 public final class Size<A> implements UnaryFunction<A, Integer>, Serializable {
32
33
34
35
36 private static final long serialVersionUID = -12374650738412129L;
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 if (obj instanceof Collection<?>) {
51 return evaluate((Collection<?>) obj);
52 }
53 if (obj instanceof String) {
54 return evaluate((String) obj);
55 }
56 if (null != obj && obj.getClass().isArray()) {
57 return evaluateArray(obj);
58 }
59 if (null == obj) {
60 throw new IllegalArgumentException("Argument must not be null");
61 }
62 throw new IllegalArgumentException("Expected Collection, String or Array, found " + obj);
63 }
64
65
66
67
68 public boolean equals(Object that) {
69 return that instanceof Size<?>;
70 }
71
72
73
74
75 public int hashCode() {
76 return "Size".hashCode();
77 }
78
79
80
81
82 public String toString() {
83 return "Size()";
84 }
85
86
87
88
89
90 public static Size<Object> instance() {
91 return INSTANCE;
92 }
93
94
95
96
97
98
99 private int evaluate(Collection<?> col) {
100 return col.size();
101 }
102
103
104
105
106
107
108 private int evaluate(String str) {
109 return str.length();
110 }
111
112
113
114
115
116
117 private int evaluateArray(Object array) {
118 return Array.getLength(array);
119 }
120
121 }