Friday, November 7, 2014

Generic Types in Java

generic type is a generic class or interface that is parameterized over types.


generic class is defined with the following format:
class name { /* ... */ }


The most commonly used type parameter names are:
  • E - Element (used extensively by the Java Collections Framework)
  • K - Key
  • N - Number
  • T - Type
  • V - Value
  • S,U,V etc. - 2nd, 3rd, 4th types

The Diamond:
Replace the type arguments required to invoke the constructor of a generic class with an empty set of type arguments (<>) as long as the compiler can determine, or infer, the type arguments from the context. This pair of angle brackets, <>, is informally called the diamond. For example, you can create an instance of Box with the following statement:
Box integerBox = new Box<>();

Multiple Types Parameter:

public interface Pair {
    public K getKey();
    public V getValue();
}

public class OrderedPair implements Pair {

    private K key;
    private V value;

    public OrderedPair(K key, V value) {
 this.key = key;
 this.value = value;
    }

    public K getKey() { return key; }
    public V getValue() { return value; }
}
The following statements create two instantiations of the OrderedPair class:
Pair p1 = new OrderedPair("Even", 8);
Pair  p2 = new OrderedPair("hello", "world");
The code, new OrderedPair, instantiates K as a String and V as an Integer. Therefore, the parameter types of OrderedPair's constructor are String and Integer, respectively. Due to autoboxing, it is valid to pass a String and an int to the class.
As mentioned in The Diamond, because a Java compiler can infer the K and V types from the declaration OrderedPair, these statements can be shortened using diamond notation:
OrderedPair p1 = new OrderedPair<>("Even", 8);
OrderedPair  p2 = new OrderedPair<>("hello", "world");

Parameterized Types

You can also substitute a type parameter (i.e., K or V) with a parameterized type (i.e., List). For example, using the OrderedPair example:
OrderedPairBox






More details at:
http://docs.oracle.com/javase/tutorial/java/generics/types.html




No comments:

Post a Comment