无码av一区二区三区无码,在线观看老湿视频福利,日韩经典三级片,成 人色 网 站 欧美大片在线观看

歡迎光臨散文網(wǎng) 會(huì)員登陸 & 注冊(cè)

泛型編程與增強(qiáng)for循環(huán)

2022-08-02 13:57 作者:限量版范兒  | 我要投稿

泛型:只在程序編譯階段起作用,給編譯器參考的,泛型的優(yōu)點(diǎn)就是統(tǒng)一了集合中的元素類型,取出元素時(shí)不太需要大量地向下轉(zhuǎn)型。但是也會(huì)導(dǎo)致集合中的元素缺乏多樣性!

package com.javastudy.example09; import javax.swing.text.html.HTMLDocument; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class FanXing { ? ?public static void main(String[] args) { ? ? ? ?//不使用泛型 ? ? ? ?List list=new ArrayList(); ? ? ? ?list.add(new Bird()); ? ? ? ?list.add(new Cat()); ? ? ? ?Iterator it=list.iterator(); ? ? ? ?while(it.hasNext()){ ? ? ? ? ? ?Object obj=it.next(); ? ? ? ? ? ?//不使用泛型 ? 向下轉(zhuǎn)型 ? ? ? ? ? ?if(obj instanceof Bird){ ? ? ? ? ? ?Bird x=(Bird)obj; ? ? ? ? ? ? ? ?x.move(); ? ? ? ? ? ?} ? ? ? ? ? ?if(obj instanceof Cat){ ? ? ? ? ? ? ? ?Cat x=(Cat)obj; ? ? ? ? ? ? ? ?x.move(); ? ? ? ? ? ?} ? ? ? ?} ? ? ? ?System.out.println("===================="); ? ? ? ?//使用泛型 ? ? ? ?List<Bird> list2=new ArrayList<Bird>(); ? ? ? ?list2.add(new Bird()); ? ? ? ?//list2.add(new Cat()); 錯(cuò)誤,不兼容 ? ? ? ?Iterator<Bird> ?it2=list2.iterator(); ? ? ? ?while(it2.hasNext()){ ? ? ? ? ? Bird b=it2.next(); ? ? ? ? ? b.move(); ? ? ? ?} //泛型的自動(dòng)類型推斷 ? ? ? ?List<Cat> list3=new ArrayList<>(); ? ? ? ?list3.add(new Cat()); ? ? ? ?//list3.add(123); 錯(cuò)誤 ? ?} } class Bird{ public void move(){ ? ?System.out.println("bird fly"); } } class Cat{ ? ?public void move(){ ? ? ? ?System.out.println("cat floot"); ? ?} }

運(yùn)行截圖

自定義泛型與增強(qiáng)for循環(huán)

package com.javastudy.example09; import java.util.ArrayList; import java.util.*; public class DiyFanX_ForEach<c123>{ ? ?public void doS(c123 x){ ? ? ? ?System.out.println(x); ? ?} public static void main(String[]args){ ? ?DiyFanX_ForEach<String> diy=new DiyFanX_ForEach(); ? ? diy.doS("123"); ? ?//增強(qiáng)for循環(huán) ? ?System.out.println("================="); ? ?List<String> list=new ArrayList<>(); ? ?list.add("123"); ? ?list.add("555"); ? ?list.add("666"); ? ?//遍歷 ? ?for(int i=0;i<list.size();i++){ ? ? ? ?System.out.println(list.get(i)); ? ?} ? ?System.out.println("================="); ? ?for (String s:list) { ? ? ? ?System.out.println(s); ? ?} ? ? ? ?} }

運(yùn)行截圖


文章鏈接:https://www.dianjilingqu.com/463768.html

泛型編程與增強(qiáng)for循環(huán)的評(píng)論 (共 條)

分享到微博請(qǐng)遵守國(guó)家法律
昂仁县| 石景山区| 荣昌县| 济南市| 色达县| 莒南县| 开平市| 宣恩县| 新邵县| 新泰市| 尤溪县| 洪泽县| 麟游县| 灵山县| 公安县| 游戏| 丹凤县| 绿春县| 名山县| 邵阳县| 新宾| 旺苍县| 江西省| 怀安县| 呈贡县| 金门县| 沙河市| 武功县| 武夷山市| 晋城| 若尔盖县| 井陉县| 崇文区| 左贡县| 璧山县| 临沧市| 阿尔山市| 蒲城县| 福贡县| 定日县| 尖扎县|