11 Template
11 Template
How to reuse the same piece of code with different data types?
myPets.add(new Integer(3));
...
Animal a = (Animal) myPets.getFirst(); ();// runtime error
The difference is that the input to formal parameters are values, while the
inputs to type parameters are types
E.g.,
Code without generics rewrite with generics
...
Pair<String> o = new Pair<String> ("1st", "2nd");
System.out.println(o.getFirst() + "," + o.getSecond());
}
...
Pair<Integer, String> o = new Pair<Integer, String> (1, “1st");
System.out.println(o.getKey() + "," + o.getValue());
T smallest = a[0];
for (int i =1; i < a.length; i++)
if (smallest > (a[i]) ) //compile error
the operator > applies only
smallest = a[i];
primitive types, cannot use
return smallest; it to compare objects!
}
}
Use a type parameter bounded by the Comparable<T> interface
public interface Comparable<T>{
public int CompareTo(T o);
}
Animal Pair<Animal>
No relationship
Cat Pair<Cat>
follows
s
static void makeASymphony( ArrayList<Animal> a){
…
}
types don’t
public static void main(String [] args){
match
ArrayList<Dog> dogs = new ArrayList<Dog>();
dogs.add(new Dog()); dogs.add(new Dog());
makeASymphony(dogs);
}
}
ArrayList<Animal> cannot changed
to ArrayList<Dog> because in
Generics there’s no such inheritance
}
}
printList(l1);
printList(l2);
e.g., List<?>
2. When the code is using methods in the generic class that don’t
depend on the type parameter
E.g, List.size(). List.clear()
It is expressed using