public class GenericTest<T> { private T t; public void add(T t) { this.t = t; } public T get() { return t; } // 泛型方法 printArray public static <E> void printArray(E[] inputArray) { // 输出数组元素 for (E element : inputArray) { System.out.printf("%s ", element); } System.out.println(); } // 比较三个值并返回最大值 public static <T extends Comparable<T>> T maximum(T x, T y, T z) { T max = x; if (y.compareTo(max) > 0) { max = y; } if (z.compareTo(max) > 0) { max = z; } return max; } public static void getData(List<?> data) { System.out.println("data :" + data.get(0)); } public static void getUperNumber(List<? extends Number> data) { System.out.println("data :" + data.get(0)); } public static void main(String args[]) { // 创建不同类型数组: Integer, Double 和 Character Integer[] intArray = { 1, 2, 3, 4, 5 }; Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 }; Character[] charArray = { 'H', 'E', 'L', 'L', 'O' }; // 传递一个整型数组 System.out.println("整型数组元素为:"); printArray(intArray); // 传递一个双精度型数组 System.out.println("\n双精度型数组元素为:"); printArray(doubleArray); // 传递一个字符型数组 System.out.println("\n字符型数组元素为:"); printArray(charArray); System.out.printf("%d, %d 和 %d 中最大的数为 %d\n\n", 3, 4, 5, maximum(3, 4, 5)); System.out.printf("%.1f, %.1f 和 %.1f 中最大的数为 %.1f\n\n", 3.3, 4.4, 5.5, maximum(3.3, 4.4, 5.5)); System.out.printf("%s, %s 和 %s 中最大的数为 %s\n", "banana", "apple", "orange", maximum("banana", "apple", "orange")); List<String> name = new ArrayList<String>(); List<Integer> age = new ArrayList<Integer>(); List<Number> number = new ArrayList<Number>(); name.add("jzh"); age.add(35); number.add(21); getData(name); getData(age); getData(number); getUperNumber(age); getUperNumber(number); GenericTest<Integer> integerBox = new GenericTest<Integer>(); GenericTest<String> stringBox = new GenericTest<String>(); integerBox.add(new Integer(17)); stringBox.add(new String("蒋智昊")); System.out.printf("整型值为 :%d\n\n", integerBox.get()); System.out.printf("字符串为 :%s\n", stringBox.get()); } }