Java 泛型進階編程 ? 類型預留位置的使用

來源:互聯網
上載者:User
 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,它根據指定比較子進行排序。

  表明在一個類體系裡,排序可以共用基類的排序方法

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.