1static void fromArrayToCollection(Object[] a, Collection<?> c) {
2 for (Object o : a) {
3 c.add(o); // compile-time error
4 }
5}
6
1public interface Pair<K, V> {
2 public K getKey();
3 public V getValue();
4}
5
6public class OrderedPair<K, V> implements Pair<K, V> {
7
8 private K key;
9 private V value;
10
11 public OrderedPair(K key, V value) {
12 this.key = key;
13 this.value = value;
14 }
15
16 public K getKey() { return key; }
17 public V getValue() { return value; }
18}
19
1Java Generic Type Naming convention helps us understanding code easily and having a naming convention is one of the best practices of Java programming language. So generics also comes with its own naming conventions. Usually, type parameter names are single, uppercase letters to make it easily distinguishable from java variables. The most commonly used type parameter names are:
2
3E – Element (used extensively by the Java Collections Framework, for example ArrayList, Set etc.)
4K – Key (Used in Map)
5N – Number
6T – Type
7V – Value (Used in Map)
8S,U,V etc. – 2nd, 3rd, 4th types
1
2List list = new ArrayList();
3list.add("abc");
4list.add(new Integer(5)); //OK
5
6for(Object obj : list){
7 //type casting leading to ClassCastException at runtime
8 String str=(String) obj;
9}
10
1
2List<String> list1 = new ArrayList<String>(); // java 7 ? List<String> list1 = new ArrayList<>();
3list1.add("abc");
4//list1.add(new Integer(5)); //compiler error
5
6for(String str : list1){
7 //no type casting needed, avoids ClassCastException
8}
9