泛型編程與增強(qiáng)for循環(huán)
泛型:只在程序編譯階段起作用,給編譯器參考的,泛型的優(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