Use Type variables
Polymorphic reverse in Java. (Earlier defined like this.)
public <T> void reverse(T[] objarr){
T tempobj;
int len = objarr.length;
for(int i=0;i< len/2 ;i++){
tempobj = objarr[i];
objarr[i] = objarr[(n-1)-i];
objarr[(n-1)-i] = tempobj;
}
}
Polymorphic find in Java. (Earlier defined like this.)
public <T> int find(T[] objarr, T o){
int i;
for(i=0;i<objarr.length;i++){
if(objarr[i]==o) { return i; }
}
return (-1);
}
Polymorphic arraycopy in Java.
public static <T> void arraycopy(T src , T tgt){
int i, limit;
limit = Math.min(src.length, tgt.length);
for(i=0;i<limit;i++){
tgt[i] = src[i];
}
}
public static <S extends T> void arraycopy(S[] src, T[] tgt){
int i, limit;
limit = Math.min(src.lenght, tgt.length);
for(i=0;i<limit;i++){
tgt[i] = src[i];
}
}
A polymorphic list
public class LinkedList<T>{
private int size;
private Node first;
public T head(){
T returnval;
....
return (returnval);
}
public void insert(T newdata) { ... }
private class Node{
private T data;
private Node next;
...
}
}
The type parameter T applies to the class as a whole in above implementation.
T in Node is the same Thead() and the argument of insert() is the same T .Instantiate generic classes using concrete type.
LinkedList<Ticket> ticketlist = new LinkedList<Ticket>();
LinkedList<Date> datelist = new LinkedList<Date>();
Ticket t = new ticket();
Date d = new Date();
ticketlist.insert(t);
datelist.insert(d);
public <T> void insert(T newdata){...} instead of the method definition here.
T in the argument of insert() is a new T<T> masks the type parameter T of LinkedList