JAVA 定義泛型類


一個泛型類

package com.zhao.generate;

/**
 * 定義泛型類  <T>不能是基本類型
 * 編寫泛型時,需要定義泛型類型<T>;
 * 靜態方法不能引用泛型類型<T>,必須定義其他類型(例如<K>)來實現靜態泛型方法
 * @param <T>
 */
public class Genericity<T> {
    public static void main(String[] args) {
        System.out.println(new Genericity<String>("100", "10").toString());
        System.out.println(Genericity.create("12", "紅絨花").toString());
    }
    private T first;
    private T last;
    public Genericity(T first, T last) {
        this.first = first;
        this.last = last;
    }
    public String toString() {
        return "Genericity{" +
                "first=" + first +
                ", last=" + last +
                '}';
    }
    // 靜態泛型方法應該使用其他類型區分:
    public static <K> Genericity<K> create(K first, K last) {
        return new Genericity<K>(first, last);
    }
    public T getFirst() {
        return first;
    }

    public void setFirst(T first) {
        this.first = first;
    }

    public T getLast() {
        return last;
    }

    public void setLast(T last) {
        this.last = last;
    }

}

多個泛型類

package com.zhao.generate;

/**
 * 定義多個泛型類
 * 泛型可以同時定義多種類型,例如Map<K, V>。
 * @param <K>
 * @param <T>
 */
public class Genericity1<K,T> {
    public static void main(String[] args) {
        Genericity1<String, Integer> g = new Genericity1<>("USER",12);
        System.out.println(g.toString());


    }
    private K first;
    private T last;
    public Genericity1(K first, T last) {
        this.first = first;
        this.last = last;
    }

    @Override
    public String toString() {
        return "Genericity1{" +
                "first=" + first +
                ", last=" + last +
                '}';
    }

    public K getFirst() {
        return first;
    }

    public void setFirst(K first) {
        this.first = first;
    }

    public T getLast() {
        return last;
    }

    public void setLast(T last) {
        this.last = last;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM