1. 程式人生 > 其它 >Java基本理解之---泛型

Java基本理解之---泛型

技術標籤:Java_basic

泛型的本質是引數型別化,解決不確定具體物件型別的問題。在面向物件程式語言中,允許程式設計師在強型別校驗下定義某些可變的部分,以達到程式碼複用的目的。

動手開幹,舉一個具體的例子,我先建立一個類,如下:

public class GenericClass {
    private String name;

    public String getName() {
        return name;
    }

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

然後編寫一個測試程式進行測試:

public class TestGenericClass {
    public static void main(String[] args) {
        GenericClass gc = new GenericClass();
        gc.setName("沒有使用泛型,當前只能是字串");
        Object obj = gc.getName();
        System.out.println(obj);

        gc.setName(110);
    }

}

在上面截圖的gc.setName(110)時,程式碼就會提示如下截圖報錯。

因此我們為了實際通用型,可以將開始的 GenericClass 改寫成如下樣子:

public class GenericClass<E> {
    private E name;

    public E getName() {
        return name;
    }

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

然後再使用:

public class TestGenericClass {
    public static void main(String[] args) {
        GenericClass gc = new GenericClass();
        gc.setName("沒有使用泛型,當前只能是字串");
        Object obj = gc.getName();
        System.out.println(obj);

        GenericClass gc2 = new GenericClass();
        gc2.setName(110);
        Object obj2 = gc2.getName();
        System.out.println(obj2);
    }
}

輸出結果如下:

沒有使用泛型,當前只能是字串
110

Process finished with exit code 0

當然我們也可以在使用的時候定義其型別,輸出的結果也一樣。

public class TestGenericClass {
    public static void main(String[] args) {
        GenericClass<String> gc = new GenericClass();
        gc.setName("沒有使用泛型,當前只能是字串");
        Object obj = gc.getName();
        System.out.println(obj);

        GenericClass<Integer> gc2 = new GenericClass();
        gc2.setName(110);
        Object obj2 = gc2.getName();
        System.out.println(obj2);
    }
}

泛型的使用,時抽象提取的開始,也是系統架構師的第一步。多多學習,多多理解。over!