1. 程式人生 > 其它 >Java-29 泛型 增強for迴圈 靜態匯入 可變引數

Java-29 泛型 增強for迴圈 靜態匯入 可變引數

  • 泛型:把明確資料型別的工作提前到編譯時期,在建立物件的時候明確。這種有點像把型別當作引數進行傳遞,所以泛型還有另外一種叫法:引數化型別
    • 格式

          <資料型別>
      注意:這裡的資料型別只能是引用資料型別

    • 好處

        1、將執行時期的問題提前到編譯時期
        2、避免了強制型別轉化    
        3、優化了程式碼程式,消除不必要的黃色警告線

import java.util.ArrayList;

public class GenericDemo1 {
    
public static void main(String[] args) { //JDK1.7之後會自動的進行型別推斷 ArrayList<String> strings = new ArrayList<>(); strings.add("hello"); strings.add("world"); // strings.add(1);//報錯 //集合遍歷 for (String string : strings) { System.out.println(string); } } }
  • 泛型的高階用法:(萬用字元)

    泛型萬用字元<?>
      任意型別,如果沒有明確,那麼就是Object以及任意的Java類了

//如果泛型裡面的型別只用一個的時候,並且明確了資料型別的時候,前後必須要寫一致
        ArrayList<Object> objects = new ArrayList<Object>();
//        ArrayList<Object> objects2 = new ArrayList<Animal>();
//        ArrayList<Object> objects2 = new ArrayList<Dog>();
// ArrayList<Object> objects3 = new ArrayList<Cat>(); //泛型萬用字元<?> //表示任意型別,如果沒有明確,那麼就是Object以及任意的Java類 //還沒有明確型別 ArrayList<?> objects1 = new ArrayList<Object>(); ArrayList<?> objects2 = new ArrayList<Animal>(); ArrayList<?> objects3 = new ArrayList<Dog>(); ArrayList<?> objects4 = new ArrayList<Cat>();

    <? extends E>
      向下限定,E及其子類

 //<? extends E>
        //向下限定,E及其子類
        ArrayList<? extends Animal> a1 = new ArrayList<Animal>();
        ArrayList<? extends Animal> a2 = new ArrayList<Dog>();
        ArrayList<? extends Animal> a3 = new ArrayList<Cat>();
//        ArrayList<? extends Animal> a4 = new ArrayList<Object>();

    <? super E>
      向上限定,E及其父類

 //<? super E>
        //向上限定,E及其父類
        ArrayList<? super Animal> animal1 = new ArrayList<Animal>();
//        ArrayList<? super Animal> animal2 = new ArrayList<Dog>();
//        ArrayList<? super Animal> animal3 = new ArrayList<Cat>();
        ArrayList<? super Animal> animal4 = new ArrayList<Object>();
  • 泛型類的使用
public class GenericClass<E> {
    private E name;

    public E getName() {
        return name;
    }

    public void setName(E name) {
        this.name = name;
    }
}



public class GenericDemo3 {
    public static void main(String[] args) {
        GenericClass<String> stringGenericClass = new GenericClass<>();

        stringGenericClass.setName("hello");
        System.out.println(stringGenericClass.getName());//hello
//        stringGenericClass.setName(12);//編譯錯誤


    }
}
  • 定義含有泛型的類
/*
泛型方法:將泛型定義方法上
            格式:public <泛型型別> 返回型別 方法名(泛型型別 .)
 */
public class GenericDemo4 {
    public static void main(String[] args) {
        GenericDemo4 genericDemo4 = new GenericDemo4();
        genericDemo4.show1(110);
        genericDemo4.show1("hello");
        genericDemo4.show1(false);

        show(112);
        show("true");
        show('h');
    }

    //定義一個泛型方法
    public  <E> void show1(E e){
        System.out.println(e);
    }

    //定義一個含有靜態方法的泛型方法
    public static <E> void show(E e){
        System.out.println(e);
    }
}
  • 定義泛型介面
    • 使用方式一 :定義介面的實現類,實現介面,指定介面的型別
    • 使用方式二:介面使用什麼泛型,實現類就使用什麼泛型,類跟著介面走
/*
        把泛型定義在介面上
        格式:public  interface 介面名<泛型型別1…>

 */

public interface Generic<T> {
    public abstract void show(T t);
}


//定義實現介面類
public class GenericClass2<T> implements Generic<T>{

    @Override
    public void show(T t) {
        System.out.println(t);
    }
}




/*
        泛型介面測試
 */
public class GenericDemo5 {
    public static void main(String[] args) {
        GenericClass2<String> stringGenericClass2 = new GenericClass2<>();
        stringGenericClass2.show("hello");//hello

        GenericClass2<Object> objectGenericClass2 = new GenericClass2<>();
        objectGenericClass2.show(1);
    }
}
  • 增強for迴圈:用來遍歷陣列和Collection集合

    增強for迴圈,JDK1.5之後出現
    到目前為止,JDK1.5之後出現的特性:泛型、增強for迴圈、包裝類(自動裝箱、自動拆箱)

  • 格式:
for(元素的資料型別 變數名 : 陣列名/Collection集合名稱){
                    使用變數即可,該變數就是元素。
            }
  • 注意:集合和陣列能使用增強for迴圈的,就使用增強for迴圈,它也可以消除黃色警告線
public class ForDemo {
    public static void main(String[] args) {
        //定義一個數組
        int[] arr = {1,2,3,4,5,6};

//        for(int i=0;i<arr.length;i++){
//            System.out.println(arr[i]);
//        }
        System.out.println("+++++++++++++增強for迴圈遍歷陣列+++++++++++++");

        for (int i : arr) {
            System.out.println(i);
        }
        System.out.println("=====================================");

        //建立一個集合物件
        ArrayList<String> strings = new ArrayList<String>();
        strings.add("hello");
        strings.add("world");
        strings.add("bigdata");
        strings.add("hive");

//        for(String string : strings){
//            System.out.println(string);
//        }
//        strings = null;

        //NullPointerException
//        for (String string : strings) {
//            System.out.println(string);
//        }

        //上面的string是不是從strings集合取出來的,而strings是null
        //所以我們在遍歷之前加一個判斷,判斷是不是空
//        if(strings != null){
//            for (String string : strings) {
//                System.out.println(string);
//            }
//        }

        //其實增強for迴圈就是用來替代迭代器的
        //如何驗證呢?
        //我們之前學迭代器的時候,遇到一個問題:併發修改異常
        //ConcurrentModificationException
        for(String s : strings){
            if("world".equals(s)){
                strings.add("flink");
            }
        }
  • 靜態匯入:
    • 格式:import static 包名….類名.方法名;
    • 注意事項:
      • 方法必須是靜態的
      • 如果說本類有其他的方法與靜態匯入的方法重名了,優先使用的是本類中的方法
      • 當靜態匯入的方法重名了,通過增加字首的方法去呼叫
public class FunctionDemo {

    public static void show(String s){
        System.out.println(s);
    }

    public static int abs(int i){
        System.out.println("這是在FunctionDemo中的abs方法");
        return i;
    }
}

/*
        靜態匯入:
            靜態匯入概述
            格式:import static 包名….類名.方法名;
            可以直接匯入到方法的級別

 */

import static java.lang.Math.abs;
import static com.shujia.java.day18.FunctionDemo.show;
import static com.shujia.java.day18.FunctionDemo.abs;
public class StaticImportDemo {
    public static void main(String[] args) {
        System.out.println(Math.abs(-100));

        //有沒有什麼辦法,不用去寫類名,直接寫方法名呼叫即可
//        System.out.println(abs(-100));
        //有一種辦法,可以不用寫類名,直接通過使用方法名呼叫
        //靜態匯入 import static java.lang.Math.abs;
//        System.out.println(abs(-200));

        //在一個程式種靜態匯入使用的方式可以和類名直接呼叫方式共存
        show("hello");//這是在本類中的show方法
        FunctionDemo.show("world");

        //當靜態匯入的方法重名了,怎麼辦呢?
        //通過增加字首的方法去呼叫
//        System.out.println(abs(20));
        System.out.println(com.shujia.java.day18.FunctionDemo.abs(20));
    }
    
    public static void show(String s){
        System.out.println("這是在本類中的show方法");
    }
}

可變引數:

/*
        可變引數概述
            定義方法的時候不知道該定義多少個引數
        格式
            修飾符 返回值型別 方法名(資料型別...  變數名){}
        注意:
            這裡的變數其實是一個數組
            如果一個方法有可變引數,並且有多個引數,那麼,可變引數肯定是最後一個

 */
public class ArgsDemo {
    public static void main(String[] args) {
        //求兩個數之和
        int a = 10;
        int b = 20;
        sum(a,b);

        //求三個數之和
        int c = 30;
        sum(a,b,c);

        //求四個數之和
        int d = 40;
        sum(a,b,c,d);

        //可變引數改進
        sum(a,b,c,d,12,32,41,2,13,141,431,31,313,89);
        
    }

    public static void sum(int... ints){
        int sum =0;
        //這裡的變數其實是一個數組
        for (int anInt : ints) {
            sum +=anInt;
        }
        System.out.println(sum);
    }

    public static void sum(int i,int j){
        System.out.println(i+j);

    }

    public static void sum(int i,int j,int x){
        System.out.println(i+j+x);

    }

    public static void sum(int i,int j,int x,int y){
        System.out.println(i+j+x+y);

    }
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/*
        Arrays工具類中的可變引數方法舉例:
            public static <T> List<T> asList(T... a):將陣列轉成集合

        1、集合與陣列之間的互相轉換
        2、陣列排序
 */
public class ArraysDemo {
    public static void main(String[] args) {
        //集合--陣列
        ArrayList<Integer> integers = new ArrayList<Integer>();
        integers.add(33);
        integers.add(44);
        integers.add(11);
        integers.add(55);
        integers.add(22);



        //將集合轉成陣列
        Object[] objects = integers.toArray();


        //陣列--集合
        List<Object> objectList = Arrays.asList(objects);
        for (Object o : objectList) {
            Integer i = (Integer)o;
            System.out.println(i);

        }

        System.out.println("******************************");
        Arrays.sort(objects);
        for (Object object : objects) {
            System.out.println(object);

        }


    }
}