java泛型問題的總結

1. 什麼是泛型?

泛型是JDK 5中引入的一個新特性,泛型提供了編譯時類型安全監測機制,該機制允許程序員在編譯時監測非法的類型。說白了就是 更好的安全性和可讀性

2. 泛型正常分爲三類

1. 泛型類
2. 泛型方法
3. 泛型接口

3. 泛型類

/*
 E表示集合的元素類型
 */

public class GenericClass<E> {
    // name是E類型的,如E爲String類型
    private E name;

    // 返回E類型的name
    public E getName() {
        return name;
    }

    // 對於參數爲E類型的name進行操作
    public void setName(E name) {
        this.name = name;
    }
}

測試:

public class GenericDemo {
    public static void main(String[] args) {
        // 創建對象時候指定爲String類型
        GenericClass<String> genericClassString = new GenericClass<>();
        genericClassString.setName("泛型爲Stirng類型");
        System.out.println(genericClassString.getName());
        // 創建對象時候指定爲Interger類型
        GenericClass<Integer> genericClassInteger = new GenericClass<>();
        genericClassInteger.setName(123);
        System.out.println(genericClassInteger.getName());
    }
}

輸出:

4.泛型方法

/*
    定義含有泛型的方法
    格式:
        修飾符 <泛型> 返回值類型 方法名稱(參數列表(使用泛型)){
            方法體;
        }
 */
public class GenericClassMethod {
    // 前面的<E>告訴jvm,我一會有一個E類型的參數要使用,別給我報錯!
    // 參數位置E m表示 ---> E類型的參數m
    public <E> void method(E m) {
        System.out.println(m);
    }
}

測試:

public class GenericDemo {
    public static void main(String[] args) {
        GenericClassMethod genericClassMethod = new GenericClassMethod();
        // 接收String類型的參數
        genericClassMethod.method("abc");
        // 接收Integer類型的參數
        genericClassMethod.method(123);
        // 接收Boolean類型的參數
        genericClassMethod.method(true);
    }
}

輸出:
在這裏插入圖片描述

5.泛型接口

定義接口

/*
    接口限制爲泛型I
 */
public interface GenericClassInterface<I> {
    public abstract void method(I i);
}

接口實現類

/*
    當實現類提前指定接口類型,可以省略實現類的泛型,如:
    public class GenericClassInterfaceImpl implements GenericClassInterface<String> {
        //...
    }
    否則依舊保持實現類中的泛型與接口泛型一致
 */
public class GenericClassInterfaceImpl<I> implements GenericClassInterface<I> {
    @Override
    public void method(I i) {
        System.out.println(i);
    }
}

測試:

public class GenericDemo {
    public static void main(String[] args) {
        GenericClassInterfaceImpl<String> gc1 = new GenericClassInterfaceImpl<>();
        gc1.method("abc");
        GenericClassInterfaceImpl<Integer> gc2 = new GenericClassInterfaceImpl<>();
        gc2.method(123);
        GenericClassInterfaceImpl<Boolean> gc3 = new GenericClassInterfaceImpl<>();
        gc3.method(true);
    }
}

輸出:
在這裏插入圖片描述

6.總結

手動實現一次,很容易理解,終於搞懂了泛型,準備下一篇高級進階。
鏈接:泛型的通配及泛型上下界<? extends T>和 <? super T>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章