Generic methods and classes enables us to specify with a single method declaration a set of related methods and with a single class declaration a set of related classes.
List list = new ArrayList(10);
list.add(“test”);
list.add(10);
list.add("java");
Display (List list){
String str=(string) list.get(0);
String str=(string) list.get(1);// runtime error will come
String str=(string) list.get(2);
List <String> list = new ArrayList <string>();
list.add(“test”);
list.add(1); // compile time error will come here
list.add(“java”);
String str1= list.get(0);
String str1= list.get(1);
String str1= list.get(2);
{ system.out.println(“astring) }
or we could use the for each loop
List <String> strings = new ArrayList <string>();
for(String astring:list)
{ system.out.println(“astring) }
Using Generic
So basically Generics forces the developer to add only specific objects to the collection to avoid runtime exception as shown in the example.
Subtyping is a concept used for wildcards declaration.
List<Integer> ints = new ArrayList<Integer>();
ints.add(2);
List<? Extends Number> nums = ints; // Allowed because of wildcards
nums.add(3.14); // This is not allowed now after setting an upperbound
Integer x=ints.get(1);
public static <T> void copy(List<? super T> dst, List<? extends T> src) {
for (int i = 0; i < src.size(); i++) {
dst.set(i, src.get(i));
}
}
The Get and Put Principle:
Comparable
interface Comparable<T> {
public int compareTo(T o);
}
Comparator
interface Comparator<T> {
public int compare(T o1, T o2);
public boolean equals(Object obj);
}
Some other Concepts
in Java, generic types are compile-time entities
primitive type parameters (Pair <int>) not allowed
objects in JVM have non-generic classes:
Pair<String> strPair = new Pair<String> . .;
Pair<Number> numPair = new Pair<Number> . .;
b = strPair.getClass () == numPair.getClass ();
assert b == true; // both of the raw class Pair