国产精品天干天干,亚洲毛片在线,日韩gay小鲜肉啪啪18禁,女同Gay自慰喷水

歡迎光臨散文網(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ó)家法律
诸暨市| 苏尼特左旗| 宜阳县| 于田县| 泽库县| 嵊州市| 娄烦县| 海盐县| 马龙县| 新邵县| 阜宁县| 探索| 宜宾县| 桓台县| 忻州市| 班戈县| 平南县| 浦东新区| 阿合奇县| 阜平县| 雷波县| 临安市| 留坝县| 大田县| 定西市| 祁连县| 吐鲁番市| 汉沽区| 鹿邑县| 北辰区| 肥乡县| 新宁县| 凤城市| 沙洋县| 卓尼县| 施秉县| 吉木萨尔县| 囊谦县| 车险| 焦作市| 呼伦贝尔市|