WildcardDemo.java.html

  1  import java.util.ArrayList;
  2  
  3  public class WildcardDemo
  4  {
  5     public static <E> void addAll(ArrayList<E> lst, ArrayList<? extends E> other)
  6     // public static <E> void addAll(ArrayList<E> lst, ArrayList<E> other)
  7     // doesn't work with Student array list
  8     {
  9        for (E e : other)
 10        {
 11           lst.add(e);
 12        }
 13     }
 14  
 15     public static <E extends Comparable<? super E>> E max(ArrayList<E> a)
 16     // public static <E extends Comparable<E>> E max(ArrayList<E> a) 
 17     // doesn't work with Student array list
 18     {
 19        E largest = a.get(0);
 20        for (int i = 1; i < a.size(); i++)
 21        {
 22           if (a.get(i).compareTo(largest) > 0) 
 23           {
 24              largest = a.get(i);
 25           }
 26        }
 27        return largest;
 28     }
 29  
 30     public static void main(String[] args)
 31     {
 32        ArrayList<Student> students = new ArrayList<Student>();
 33        students.add(new Student("Fred", "CS"));
 34        students.add(new Student("Ann", "Bio"));
 35        students.add(new Student("Sue", "CS"));
 36  
 37        ArrayList<Person> people =  new ArrayList<Person>();
 38        people.add(new Person("Harry"));
 39  
 40        addAll(people, students);
 41        System.out.println(people);
 42  
 43        System.out.println(max(students));      
 44     }
 45  }