Core Java 中的泛型实例

(一)

package com.learn.corejava.generic;



public class Pair<T> {

    private T first;

    private T second;



    public Pair() {

    }



    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;

    }

}


Pair<String> pair = new Pair<>("key", "value");

System.out.println(pair.getFirst());



Pair<Integer> intPair = new Pair<>(10, 20);

System.out.println(intPair.getFirst());


(二)

package com.learn.corejava.generic;



public class PairTwo<T, U> {

    private T first;

    private U last;



    public PairTwo(T first, U last) {

        this.first = first;

        this.last = last;

    }



    public T getFirst() {

        return first;

    }



    public void setFirst(T first) {

        this.first = first;

    }



    public U getLast() {

        return last;

    }



    public void setLast(U last) {

        this.last = last;

    }

}


PairTwo<String, Integer> pt = new PairTwo<>("v", 30);

System.out.println(pt.getFirst() + " - " + pt.getLast());


(三)

package com.learn.corejava.generic;



import java.io.Serializable;



public class ArrayAlg {



    // 需要先定义 <T> 

    public static <T extends Comparable & Serializable> T min(T[] a) {

        if (a == null || a.length == 0) {

            return null;

        }

        T smallest = a[0];

        for (int i = 0; i < a.length; i++) {

            if (smallest.compareTo(a[i]) > 0) {

                smallest = a[i];

            }

        }

        return smallest;

    }



    public static <T extends Comparable> Pair<T> minmax(T[] a) {

        if (a == null || a.length == 0) {

            return null;

        }

        T min = a[0];

        T max = a[0];

        for (int i = 0; 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);

    }

}


LocalDate[] birthdays = {

        LocalDate.of(1906, 12, 9),

        LocalDate.of(1992, 10, 10),

        LocalDate.of(2020, 2, 1)

};

Pair mm = ArrayAlg.minmax(birthdays);

System.out.println(mm.getFirst() + " " + mm.getSecond());


 

展开阅读全文