泛型

相当于将数据类型参数化
泛型只作用于编译期,在编译后会被所指定的具体类型代替

//定义一个泛型类
public class Node<T> {

	private T data;//泛型,参数化数据类型
	
	public Node() {}
	
	public Node(T data) {
		this.data = data;
	}
	
	public T getData() {
		return data;
	}
	
	public T setData() {
		return data;
	}
}

public class GenericDemo {

	public static void main(String[] args) {
		
		testNode();
	}

	private static void testNode() {
		
		Node<String> strNode = new Node<String>("一二三四五六七八九十");
		Node<Number> numNode = new Node<Number>(10);
		Node<Integer> intNode = new Node<Integer>(10);
		
		System.out.println(strNode.getData());
		System.out.println(numNode.getData());
		System.out.println(intNode.getData());
	}
}

同一个泛型类但不同数据类型,两者之间无法进行转换,此时可以使用通配符处理?表示可以接收任意的泛型类型,但是只能接收输出,不能修改和赋值

public void test() {
		Node<Number> n1 = new Node<Number>(10);
		Node<Integer> n2 = new Node<Integer>(20);
		
		getData(n1);
//		getData(n2);//报错
	}
	
public static void getData(Node<Number> node) {
	System.out.println(node.getData());
}
	
//通配符
public static void getData2(Node<?> node) {
		
//	node.setData(123);//用来赋值会报错
	System.out.println(node.getData());//只能用于读取
}

//泛型上限,表示所能接收类型只能是指定类或其子类(使用关键字extends)
//泛型下线,表示所能接收类型只能是指定类或其父类(使用关键字super)
public static void getData3(Node<? extends Number> node){
	System.out.println(node.getData());
}

泛型还可以定义在方法中

public static void test2() {
	String[] arrays = {"blink","lubricate","bottle"};
	String[] s = func(arrays,0,2);
	System.out.println(Arrays.toString(s));		
}
//泛型方法
public static <T> T[] func(T[] array,int i,int j){
	T temp = array[i];
	array[i] = array[j];
	array[j] = temp;
return array;
	}

泛型的嵌套使用:

//嵌套
public static void test3() {
	Map<Integer,String> map = new HashMap<Integer, String>();
	map.put(1, "coco");
	map.put(2, "csocso");
		
	Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
	for(Map.Entry<Integer, String> entry:entrySet) {
		System.out.println(entry.getKey()+"-"+entry.getValue());
	}
}