java集合架構---泛型總結

來源:互聯網
上載者:User

標籤:泛型   java   

/* 泛型:指定集合類型,在運行而不是編譯時間時就發現問題,消除安全隱患。避免強轉。 */package pack;import java.util.ArrayList;import java.util.Iterator;/*public class Main {    public static void sys(Object obj) {        System.out.println(obj);    }    public static void main(String[] args) {        TreeSet<String> al = new TreeSet<String>(new MyComparator());  //集合泛型        al.add("aa");        al.add("bbb");        al.add("c");        Iterator<String> it = al.iterator();        while(it.hasNext()) {            String s = (String)it.next();  //避免強轉            sys(s);            sys(it.next());        }    }}class MyComparator implements Comparator<String> {    public int compare(String o1,String o2) {        int a = new Integer(o2.length()).compareTo(new Integer(o1.length()));        if(a==0) {            return o2.compareTo(o1);        }        return a;    }}*//*public class Main {    public static void main(String[] args) {        Demo<Integer> d = new Demo<Integer>();        d.show(4);        d.show(new Integer(5));        Demo<String> d1 = new Demo<String>();        d1.show("haha");    }}class Demo<T> {      //泛型方法,當前不知定義什麼類型    public void show(T t) {        System.out.println(t);    }}*//*interface Inter<T> {   //泛型介面    void show(T t);}class Demo<T> implements Inter<T> {    public void show(T t) {        System.out.println(t);    }}public class Main {    public static void main(String[] args) {        Demo<Integer> d = new Demo<Integer>();        d.show(new Integer(3));    }}*/public class Main {    public static void main(String[] args) {        ArrayList<String> al1 = new ArrayList<String>();        al1.add("java1");        al1.add("java2");        al1.add("java3");        ArrayList<Integer> al2 = new ArrayList<Integer>();        al2.add(1);        al2.add(2);        al2.add(3);        show(al1);        show(al2);    }    public static <T> void show(ArrayList<T> a) { //T可以用?代替        Iterator<T> it = a.iterator();        while(it.hasNext()) {            System.out.println(it.next());        }    }}

java集合架構---泛型總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.