• Remember Structural Polymorphism.
  • We need Polymorphic Data Structures.

  • 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;
      	}
      }
      
      • Type quantifier before the return type → “For Every type T …”

    • 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);
      }
      
      • Searching for a value of incompatible type is now a compile-time error.

    • 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];
      	}
      }
      
      • Source and target types must be identical above.
      • For the condition: Source type must extend the target type→ we can include relationship for the type:
      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.

        • Internally the T in Node is the same T
        • The return values of the method head() 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);
        

  • Be careful not to accidentally hide a type variable: public <T> void insert(T newdata){...} instead of the method definition here.
    • T in the argument of insert() is a new T
    • Quantifier <T> masks the type parameter T of LinkedList