Java中使用泛型

  • 泛型类

package 泛型类;

public class Pair<T> {
    private T first;
    private T second;

    public Pair() {
        first = null;
        second = null;
    }

    public Pair(T first, T second) {
        this.first = first;
        this.second = second;
    }

    public T getFirst() {
        return first;
    }

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

    public T getSecond() {
        return second;
    }

    public void setSecond(T second) {
        this.second = second;
    }
}
package 泛型类;

public class PairTest1 {
    public static void main(String[] args) {
        String[] words = {"Mary", "Had", "a", "little", "lamb"};
        Pair<String> mm = ArrayAlg.minmax(words);
        System.out.println(mm.getFirst());
        System.out.println(mm.getSecond());
    }
}

class ArrayAlg {
    public static Pair<String> minmax(String[] a) {
        if (a == null || a.length == 0) return null;
        String min = a[0];
        String max = a[0];
        for (int i = 1; i < a.length; i++) {
            if (min.compareTo(a[i]) > 0) min = a[i];
            if (max.compareTo(a[i]) < 0) max = a[i];
        }
        return new Pair<>(min, max);
    }
}
  • 泛型方法

package 泛型类;

public class PairTest1 {
    public static void main(String[] args) {
        //String middle = ArrayAlg.<String>getMiddle("John", "Q.", "Public");
        String middle = ArrayAlg.getMiddle("John", "Q.", "Public");
        System.out.println(middle);
    }
}

class ArrayAlg {
    public static <T> T getMiddle(T... a) {
        return a[a.length / 2];
    }
}
  • 类型变量的限定

public static <T extends Comparable & Serializable> Pair<T> minmax(T[] a) {
    if (a == null || a.length == 0) return null;
    T min = a[0];
    T max = a[0];
    for (int i = 1; i < a.length; i++) {
        if (min.compareTo(a[i]) > 0) min = a[i];
        if (max.compareTo(a[i]) < 0) max = a[i];
    }
    return new Pair<>(min, max);
}
posted @ 2020-04-18 13:29  xl4ng  阅读(144)  评论(0编辑  收藏  举报