Generics
Generics were introduced in java 5 to add stability to the code. You can add type variables to classes, interfaces and methods.
Generic Class Declaration
Below you see an example of generic class declaration. by writing class Box<T>
, you introduce the type parameter T
, that can be used anywhere in the class.
public class Box<T> {
private T t;
public void set(T t){ this.t = t; }
public T get(){ return t; }
}
Generic type invocation
To reference the generic Box
class you must perform a generic type invocation, by passing a concrete type argument. To instantiate the class, use the new keyword as usual, but place the correct type argument before the parenthesis.
Starting from Java 7, you can replace the type arguments with an empty set of type arguments <>
, the diamond operator, as long as the compiler can infer the type arguments from the context.
Box<Integer> intBox;// reference
intBox = new Box<Integer>();// instantiate, Java 5
intBox = new Box<>();// instantiate, Java 7
Multiple type parameters
A generic type (class or interface), can have multiple type parameters. Below, you can see a simple example where we define two generic types.
public interface Entry<K,V>{
public K getKey();
public V getValue();
}
public class EntryImpl<K,V>{
private K key;
private V value;
public EntryImpl(K key, V value){
this.key = key;
this.value = value;
}
public K getKey(){ return key; }
public V getValue(){ return value; }
}
The instantiation is pretty straightforward.
EntryImpl<String, Integer> e1 = new EntryImpl<>("first", 1);
EntryImpl<String, String> e2 = new EntryImpl<>("second", "two");
Parametrized Types
You can substitute a type parameter with a parametrized type, as you can see in the example below.
EntryImpl<String, Box<String>> entry = new EntryImpl<>("entry", new Box<Integer>(10));
Raw Types
A raw type is a generic type without any type argument. Below you can see an example of raw type usage for the previously defined Box<T>
.
Box rawBox = new Box(); // raw type
Box<Integer> intBox = rawBox; //warning: unchecked conversion
The java compiler emits a warning when you use a raw type.
Generic Methods
Generic methods are methods that introduce their own type parameters. The parametrization is much like declaring a generic type, whereas the type parametrs scope is limited to the method where is declared.
public class Util{
public static <K, V> boolean compare(Entry<K,V> e1, Entry<K, V> e2){
return e1.getKey().equals(e2.getKey())&&
e1.getValue.equals(e2.getValue());
}
}
Usually, you can invoke the method with its complete syntax, specifying explicitly the types. Alternatively, if the type can be inferred, you can invoke the method as an ordinary method, without specifying the type.
Entry<String, Integer> e1 = new EntryImpl<>("first", 1);
Entry<String, Integer> e2 = new EntryImpl<>("second", 2);
// complete syntax
boolean cmp = Util<String,Integer>.compare(e1, e2);
// type can be inferred
boolean cmp2 = Util.compare(e1, e2);
0 Comments