Java >> Generics
Source: https://docs.oracle.com/javase/tutorial/java/generics
Definition: Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods.
*** How do you expect the class to take parameters? Do you expect an Integer or a String?
Benefits:
- Stronger type checks at compile time
- Elimination of casts
- Enabling programmers to implement generic algorithms.
Type parameter convention:
E - Element (in Collections)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types
Example:
public interface Pair<K, V> {
public K getKey();
public V getValue();
}
public class OrderedPair<K, V> implements Pair<K, V> {
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; }
}
Raw type:
is the name of a generic class or interface without any type arguments
Generic methods:
are methods that introduce their own type parameters
Example:
public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) {
return p1.getKey().equals(p2.getKey()) &&
p1.getValue().equals(p2.getValue());
}
Bounded Type Parameters:
are used to restrict the types that can be used as type arguments in a parameterized type
Example:
public <U extends Number> void inspect(U u);
Generic algorithm:
public interface Comparable<T> {
public int compareTo(T o);
}
public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {
int count = 0;
for (T e : anArray)
if (e.compareTo(elem) > 0)
++count;
return count;
}
*** T extends Comparable<T> is interpreted as follows: I expect the type T, but T also has to implement an interface which applies on T