1 | package dmg.util; |
2 | |
3 | import java.util.Map; |
4 | import java.util.List; |
5 | import java.util.Set; |
6 | import java.util.SortedSet; |
7 | import java.util.SortedMap; |
8 | import java.util.HashMap; |
9 | import java.util.HashSet; |
10 | import java.util.TreeMap; |
11 | import java.util.TreeSet; |
12 | import java.util.ArrayList; |
13 | import java.util.concurrent.CopyOnWriteArrayList; |
14 | import java.util.concurrent.ConcurrentHashMap; |
15 | import java.util.concurrent.BlockingQueue; |
16 | import java.util.concurrent.LinkedBlockingQueue; |
17 | |
18 | /** |
19 | * Utility class containing static factory methods for common Java |
20 | * collections. Using the factory methods avoids the problem that Java |
21 | * does not support type inference for constructors. The following would |
22 | * give a compiler warning: |
23 | * |
24 | * List<String> l = new ArrayList(); |
25 | * |
26 | * however using the factory method avoids the warning: |
27 | * |
28 | * List<String> l = CollectionFactory.newArrayList(); |
29 | * |
30 | * The alternative would be to use: |
31 | * |
32 | * List<String> l = new ArrayList<String>(); |
33 | * |
34 | * This does however violate the DRY principle, as the type needs to |
35 | * be repeated. |
36 | */ |
37 | public class CollectionFactory |
38 | { |
39 | private CollectionFactory() |
40 | { |
41 | } |
42 | |
43 | public static <K,V> Map<K,V> newHashMap() |
44 | { |
45 | return new HashMap<K,V>(); |
46 | } |
47 | |
48 | public static <K,V> SortedMap<K,V> newTreeMap() |
49 | { |
50 | return new TreeMap<K,V>(); |
51 | } |
52 | |
53 | public static <K,V> Map<K,V> newConcurrentHashMap() |
54 | { |
55 | return new ConcurrentHashMap<K,V>(); |
56 | } |
57 | |
58 | public static <V> Set<V> newHashSet() |
59 | { |
60 | return new HashSet<V>(); |
61 | } |
62 | |
63 | public static <V> SortedSet<V> newTreeSet() |
64 | { |
65 | return new TreeSet<V>(); |
66 | } |
67 | |
68 | public static <V> List<V> newArrayList() |
69 | { |
70 | return new ArrayList<V>(); |
71 | } |
72 | |
73 | public static <V> List<V> newCopyOnWriteArrayList() |
74 | { |
75 | return new CopyOnWriteArrayList<V>(); |
76 | } |
77 | |
78 | public static <V> BlockingQueue<V> newLinkedBlockingQueue() |
79 | { |
80 | return new LinkedBlockingQueue<V>(); |
81 | } |
82 | } |