泛型

泛型的本質是“數據類型的”參數化,處理的數據類型不是固定 的,而是可以作為參數傳入。
我們可以把“泛型”理解為數據類型的一個占位符(類似形式參數),即告訴編譯器,在調用泛型是必須傳入實際類型。
這種參數類型可以用在類、接口和方法中,分別被稱為泛型類、泛型接口、泛型方法。

1.泛型類

public class TestGeneric<T> {
    private T t;
    public T getT() {
        return t;
    }

    public void setT(T t) {
        this.t = t;
    }

    public Test1(T t) {
        this.t = t;
    }
}

class Main{
    public static void main(String[] args) {
        //T -> String
        TestGeneric<String> testGeneric = new TestGeneric<String>("hello");
        String t = testGeneric.getT();
    }
}

2.泛型方法

用在調用方式的時候指明泛型的具體類型.
語法:

修飾符 <T,E,......> 返回值類型 方法名(形參列表){
}
    //<T> 泛型列表
    public  <T> T getE(T e){
        return e;
    }

3.泛型接口

interface TestInterface<T> {
    void interfacePrint(T t);
}

class TestInterfaceImpl1 implements TestInterface<String> {
    @Override
    public void interfacePrint(String s) {
        System.out.println("實現類非泛型,指定TestInterface泛型類型: " + s);
    }
}

class TestInterfaceImpl2<T, E> implements TestInterface<T> {

    E e;

    public TestInterfaceImpl2(E e) {
        this.e = e;
    }

    public void dd(){

    }

    @Override
    public void interfacePrint(T t) {
        System.out.println("實現類是泛型,泛型包含TestInterface的泛型類型: " + t);
    }
}

class Main1 {
    public static void main(String[] args) {
        TestInterfaceImpl1 integerTestInterface1 = new TestInterfaceImpl1();
        integerTestInterface1.interfacePrint("hello");

        TestInterfaceImpl2<Integer, String> integerTestInterface2 = new TestInterfaceImpl2<>("hello");
        integerTestInterface2.interfacePrint(222);

    }
}

4.類型通配符 "?"

class Box<E>{
    private E e;

    public E getE() {
        return e;
    }

    public void setE(E e) {
        this.e = e;
    }
}

class Main2{
    public static void main(String[] args) {
        Box<Number> numberBox = new Box<>();
        numberBox.setE(100);
        showBox(numberBox);

        Box<Integer> integerBox = new Box<>();
        integerBox.setE(200);
        showBox(integerBox);
    }

    //? extends Number 類型通配符;super下限
    public static void showBox(Box<? extends Number> box){
        Number e = box.getE();
        System.out.println(e);

    }
}

<T extends A>就是我不知道“T”具體是啥,但是我知道它的父類是A
<? extends A>和上面一個效果

區別:
<T extends A>用于聲明;<? extends A>單獨使用的時候用

public class Test<T extends A> {}

public void haha(List<? extends A> strs){}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容