import java.util.*;class Person{private String name;private int age;public Person (String name,int age){this.name=name;this.age=age;}public String getName(){return this.name;}public int getAge(){return this.age;}public String toString (){return this.getName()+"..."+this.getAge();}}class Student extends Person{public Student(String name,int age){super(name,age);}public String getName(){return super.getName();}}public class Zhanweifu {public static void main(String args[]){ArrayList<Person> personlist =new ArrayList<Person>();ArrayList<Student>studentlist=new ArrayList<Student>();personlist.add(new Person ("boy",20)); studentlist.add(new Student("stu-boy",20));personlist.add(new Person ("girl",22)); studentlist.add(new Student("stu-girl",22));personlist.add(new Person("person",30)); studentlist.add(new Student("stu-person",30));personlist.add(new Student ("boy",20));//print(personlist);//print(studentlist);傳studentlist 將會出現編譯錯誤//sop(personlist);//show(personlist);//show(studentlist);display(personlist);display(studentlist);}public static void print(ArrayList<Person> list) //這是為ArrayList<Person> 量身定做列印,沒有什麼擴充性{for(Iterator<Person> it=list.iterator();it.hasNext();){System.out.println(it.next());}}public static void sop(ArrayList<?> list) //直接利用預留位置對操作類型進行佔位,對任意類型的ArrayList<> 都可以操作,原理和泛型方法差不多{for(Iterator<?>it=list.iterator();it.hasNext();){System.out.println(it.next());}}public static void show(ArrayList<? extends Person> list)//通過預留位置來限制參數的類型 ,extends Person 表示 參數只能是Person 或Person 類的子類{for(Iterator<? extends Person> it=list.iterator();it.hasNext();){System.out.println(it.next());}}public static void display(ArrayList<? super Student> list)//通過預留位置來限帛參數的類型,super Student 表示參數只能是Student,或Student類的父類{for(Iterator<? super Student> it=list.iterator();it.hasNext();){System.out.println(it.next());2011/10/27 20:57:44}}}
TreeSet(Collection<? extends E> c) 構造一個包含指定 collection 元素的新 TreeSet,它按照其元素的自然順序進行排序。 |
TreeSet(Comparator<? super E> comparator) 構造一個新的空 TreeSet,它根據指定比較子進行排序。 |
表明在一個類體系裡,排序可以共用基類的排序方法