Java之泛型

1、为什么要有泛型Generic?

2、 总结

Java中的泛型,只在编译阶段有效。在编译过程中,正确检验泛型结果后,会将泛型的相关信息擦出,并且在对象进入和离开方法的边界处添加类型检查和类型转换的方法。也就是说,泛型信息不会进入到运行时阶段。

3、泛型的使用

1..泛型类
2.泛型方法
3.泛型接口

3.1 泛型类

public class Person {
	public static void main(String[] args) {
		A<String> key = new A<String>();//在new A的对象指定泛型的类型为String
		key.setKey("李四");//对象使用setKey(T key)方法,中的key形参就是String
		
		A<Integer> key1 = new A();
		key1.setKey(20);
		System.out.println(key1.getKey());
		
		A key2 = new A();//不指定泛型,代表泛型类型为object类型
		key2.setKey(new Object());
		
	
		//相同的类,但在new对象的时候,指定不同的泛型时,不能相互赋值
		//key = key1;
	}
}
class A<T>{
	private T key;
	private int age;
	
	public void setKey(T key) {
		this.key = key;
	}
	
	public T getKey() {
		return this.key;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
}

3.2 泛型接口

public class Test {
	public static void main(String[] args) {
		//未传入实参的类,创建对象时,指定泛型类型
		B1<Integer>b1 = new B1();
		b1.test(11);
		
		//传入实参的类,创建对象时,不能传入泛型类型,因为定义类时,已经定义过类型了
		B2 b2 = new B2();
		b2.test("李四");
	}
}

//接口泛型
interface IB<T> {
	T test(T t);
}

/**
 * 未传入泛型实参时,与泛型类的定义相同,在声明类的时候,需要将泛型的声明也一起加到类中
 * @author Zw
 *
 * @param <T>
 */
class B1<T> implements IB<T>{

	@Override
	public T test(T t) {		
		return t;
	}
	
}

/**
 * 如果实现接口时指定接口的泛型的具体数据类型
 * 这个类实现接口的所有方法的位置都要泛型替换实际的具体数据类型
 * @author Zw
 *
 */
class B2 implements IB<String>{

	@Override
	public String test(String t) {		
		return t;
	}
	
}

3.3 泛型方法

方法,也可以被泛型化,不管此时定义在其中的类是不是泛型化的。在泛型方法中可以定义泛型参数,此时,参数的类型就是传入数据的类型。

public class Test1 {
	public static void main(String[] args) {
		Cc<Object> c = new Cc<Object>();
		/**
		 * 泛型方法,在调用之前没有固定的数据类型
		 * 在调用时,传入的参数是什么类型,就会把泛型改成什么类型
		 */
		c.test(11);
		c.test1("test");
		c.test2(1,3,4);
		//可变参数:list集合
		List<String> list = new ArrayList<String>();
		list.add("王二");
		list.add("李四");
		c.test2(list);
		
		//可变参数:数组
//		int[] array = new int[3];
//		int [] array1 = {11,13,15};
//		System.out.println(array1);
//		c.test2(array1[1]);
		
		
	}
}

class Cc<E>{
	private E e;
	/**
	 * 无返回值的泛型方法
	 * @param <T>
	 * @param s
	 */
	public<T> void test(T s) {
		//在类上定义的泛型,可以在普通的方法中使用
		System.out.println(this.e);
	}
	//在静态方法中,不能使用类定义的泛型,如果要使用泛型,只能使用静态方法自己定义的泛型
	public static<T> void test3(T t) {
		System.out.println(t);
	}
	/**
	 * 有返回值的泛型方法
	 * @param <T>
	 * @param s
	 * @return
	 */
	public<T> T test1(T s) {
		return s;
	}
	
	/**
	 * 可变参数的泛型方法
	 * @param <T>
	 * @param args
	 */
	public<T> void test2(T... args) {
		for(T s:args) {
			System.out.println(s);
		}
	}
}
原文地址:https://www.cnblogs.com/istart/p/12031993.html