Java集合遍歷實(shí)現(xiàn)方法及泛型通配
集合定義
集合,集合是java中提供的一種容器,可以用來(lái)存儲(chǔ)多個(gè)數(shù)據(jù)。
特點(diǎn):數(shù)組的長(zhǎng)度是固定的。集合的長(zhǎng)度是可變的。集合中存儲(chǔ)的元素必須是引用類型數(shù)據(jù)‘
普通for遍歷:
//案例一ArrayList<Person> arr=new ArrayList<Person>(); arr.add(new Person('張三',19)); arr.add(new Person('小紅帽',20)); arr.add(new Person('小紅帽',23)); for(int i=0;i<arr.size();i++){ System.out.println(arr.get(i)); }
增強(qiáng)for循環(huán)遍歷:
案例二 Collection<Integer> arr=new ArrayList<Integer>(); arr.add(789); arr.add(456); arr.add(123); //增強(qiáng)for循環(huán) /*for(元素的數(shù)據(jù)類型 變量 : Collection集合or數(shù)組){ }*/ for(Integer i:arr){ System.out.println(i); }
迭代器遍歷:
//案例三//1,創(chuàng)建集合對(duì)象。Collection<String> coll = new ArrayList<String>();coll.add('abc1');coll.add('abc2');coll.add('abc3');coll.add('abc4'); //2.獲取容器的迭代器對(duì)象。通過(guò)iterator方法。Iterator it = coll.iterator(); //3,使用具體的迭代器對(duì)象獲取集合中的元素。參閱迭代器的方法while(it.hasNext()){ System.out.println(it.next());}
Collection接口的基本方法
Collection接口是集合中的頂層接口,那么它中定義的所有功能子類都可以使用

創(chuàng)建集合的格式:
方式1:Collection<元素類型> 變量名 = new ArrayList<元素類型>();
方式2:Collection 變量名 = new ArrayList();
集合元素的向下轉(zhuǎn)型
Collection coll = new ArrayList();coll.add('abc');coll.add('aabbcc');coll.add(1);Iterator it = coll.iterator();while (it.hasNext()) { //由于元素被存放進(jìn)集合后全部被提升為Object類型//當(dāng)需要使用子類對(duì)象特有方法時(shí),需要向下轉(zhuǎn)型 String str = (String) it.next(); System.out.println(str.length());}
泛型和通配符
類定義格式:修飾符 class 類名<代表泛型的變量> { }
接口定義格式:修飾符 interface接口名<代表泛型的變量> { }
限定泛型的下限:
//? extends Person 限定泛型的上限 //? super Person 限定泛型的下限 public static void get(Collection<? extends Person> c){ Iterator<?> it=c.iterator(); while(it.hasNext()){ //向下轉(zhuǎn)型 Object obj=it.next(); Person p=(Person)obj; System.out.println(p.getName()); }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python 合并拼接字符串的方法2. Linux刪除系統(tǒng)自帶版本Python過(guò)程詳解3. Python3 json模塊之編碼解碼方法講解4. Python 制作查詢商品歷史價(jià)格的小工具5. python 使用事件對(duì)象asyncio.Event來(lái)同步協(xié)程的操作6. ASP基礎(chǔ)知識(shí)VBScript基本元素講解7. ASP.NET MVC使用jQuery ui的progressbar實(shí)現(xiàn)進(jìn)度條8. Python 利用Entrez庫(kù)篩選下載PubMed文獻(xiàn)摘要的示例9. Python sublime安裝及配置過(guò)程詳解10. Python插件機(jī)制實(shí)現(xiàn)詳解

網(wǎng)公網(wǎng)安備