类型安全: generics v.s arrays (二)

代码实例: 一个类型安全的过滤器

 

 1 import java.util.ArrayList;
2 import java.util.Arrays;
3 import java.util.Collection;
4 import java.util.List;
5
6 /**
7 * A sample usage :
8 * <code><pre>
9 * Filter.Checker&lt;Object&gt; checker = new Filter.Checker&lt;Object&gt;() {
10 * public boolean check(Object value) {
11 * return String.valueOf(value).contains("3");
12 * }
13 * };
14 *
15 * List&lt;String&gt; strWith3s = Filter.filt(
16 * checker,
17 * "1 + 2 = 3",
18 * "2 + 3 = 4",
19 * "oops, 2 + 3 = 5",
20 * "3 + 5 = 8",
21 * "5 + 8 = 13"
22 * );
23 *
24 * List&lt;Number&gt; numsWith3s = Filter.&lt;Number&gt;filt(
25 * checker, Arrays.asList(new Integer[]{ 1, 2, 3, 12, 13, 23 })
26 * );
27 * </pre></code>
28 *
29 * @author 那十无忧
30 */
31 public class Filter {
32
33 // strategy interface
34 public interface Checker<V> {
35
36 public boolean check(V value);
37 }
38
39 public static <E> List<E> filt(Checker<? super E> checker,
40 Collection<? extends E> values) {
41 assert checker != null;
42
43 if( values == null ) return null;
44
45 @SuppressWarnings("unchecked")
46 E[] snapshot = (E[])values.toArray(new Object[values.size()]);
47
48 List<E> result = new ArrayList<E>(snapshot.length);
49
50 for(E e : snapshot)
51 if( checker.check(e) )
52 result.add(e);
53 snapshot = null;
54 return result;
55 }
56
57 public static <E> List<E> filt(Checker<? super E> checker, E... values) {
58 if( values == null ) return null;
59
60 return filt(checker, Arrays.asList(values));
61 }
62 }



你可能感兴趣的:(类型安全: generics v.s arrays (二))