8.11 Java 泛型

和C++的 template 类似


public class Mine {
	static <T> void pln(T x) {
		System.out.println(x);
	}
	public static <T> void printArray(T[] Array) {
		for(T element : Array) {
			System.out.printf("%s ", element);
		}
		System.out.println();
	}
	public static void main(String[] args) {
		Integer[] intArray = {1,2,3,4,5};
		Double[] doubleArray = {1.1,2.2,3.3,4.4};
		Character[] charArray = {'N','O','Z','O','M','I'};
		pln("[INTEGER]");
		printArray(intArray);
		pln("");
		pln("[DOUBLE]");
		printArray(doubleArray);
		pln("");
		pln("[CHAR]");
		printArray(charArray);
		pln("");
	}
}

泛型+可变个数参数 实现MAX任意化
由于要实现比较 所以 用 T extends Comparable 继承 compareTo方法


public class Mine{
	public  static <T> void pln(T x) {
		System.out.println(x);
	}
	public static <T extends Comparable<T>> T MAX(T... x) {
		T maxx = x[0];
		for(T element : x) {
			if (element.compareTo(maxx) > 0) {
				maxx = element;
			}
		}
		return maxx;
	}
	public static void main(String[] args) {
		pln(MAX(1, 2, 3));
		pln(MAX(1.2, 2.2, 3.3, 4.4));
		pln(MAX("Nozomi","Mizore","Reina","Kumiko"));
	}
}

泛型类


class Box<T>{
	private T x;
	public void add(T x) {
		this.x = x;
	}
	public T get() {
		return x;
	}
}
public class Mine{
	public  static <T> void pln(T x) {
		System.out.println(x);
	}
	
	public static void main(String[] args) {
		Box<Integer> integerBox = new Box<Integer>();
		Box<String> stringBox = new Box<String>();
		integerBox.add(1);
		stringBox.add("Nozomi");
		
		System.out.printf("[INTEGER]: %d\n", integerBox.get());
		System.out.printf("[STRING]: %s\n", stringBox.get());
	}
}
posted @ 2023-08-11 17:29  N0zoM1z0  阅读(3)  评论(0编辑  收藏  举报