public class Generic<T> { public Generic() { head = null; tail = null; } public Generic(T head, T tail) { this.head = head; this.tail = tail; } public T getHead() { return head; } public void setHead(T head) { this.head = head; } public T getTail() { return tail; } public void setTail(T tail) { this.tail = tail; } private T head; private T tail; }
public class GenericTest { public static <T extends Comparable> Generic<T> minmax(T[] a) { if (a == null || a.length == 0) { return null; } T max = a[0]; T min = 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 Generic<T>(min, max); } public static void main(String[] args) { GregorianCalendar[] date = { new GregorianCalendar(1903,Calendar.FEBRUARY,9), new GregorianCalendar(1815,Calendar.JUNE,18), new GregorianCalendar(1910,Calendar.JULY,9), }; Generic<GregorianCalendar> gg = minmax(date); System.out.println(gg.getHead().getTime()+"\n"+gg.getTail().getTime()); /*String[] words = { "Marry", "Jim", "Xie", "littlep" }; Generic<String> mm = minmax(words); System.out.println("min = " + mm.getHead() + "\n" + "max = " + mm.getTail());*/ } }