JAVA常用特性:泛型基础

目录

泛型:

泛型在类/接口中的使用:

泛型方法的定义:

泛型通配符的使用:


泛型:

早期的Object类型可以接收任意的对象类型,但是在实际的使用中,会有类型转换的问题。也就存在这隐患,所以Java提供了泛型来解决这个安全问题。

泛型可以修饰接口、以及泛型方法

泛型类型必须是引用类型

泛型在类/接口中的使用:

public class GenericDemo01 {
	public static void main(String[] args) {
		Box box = new Box();    //未定义泛型时,对象类似是Object类型。但会有警告
		box.setData(100);
		Object o = box.getData();
		Box<Object> box1 = new Box<>(); //设置Object类型的泛型,警告消除。
		box1.setData(100);
		Object o1 = box.getData();
		System.out.println(box.getClass().getName()); //com._51doit.javase05.day14.genericdemo.Box


		Box<String> box1 = new Box<>("123");  //此时对象为String类型
		System.out.println(box1.getData());  //123
		System.out.println(box1.getClass().getName()); //com._51doit.javase05.day14.genericdemo.Box
	}	
}
//泛型定义在类上
class Box<T>{
	T data; //成员变量	
	public Box() {}
	public Box(T data) {    //构造方法
		this.data = data;
	}
	public T getData() {    //成员方法:类中使用泛型,并不是定义了泛型的方法
		return data;
	}
}
//泛型定义在接口上
interface Inter<B>{
	void test(B b);  //抽象方法
}

泛型在实现接口时的注意事项:

interface Inter<B>{
	void test(B b);  //抽象方法
}
//泛型中实现泛型接口的两种注意事项
class Test<B> implements Inter<B>{
	@Override
	public void test(B b) {
		System.out.println("风花雪月");		
	}	
}
class Test1 implements Inter<String>{
	@Override
	public void test(String b) {
		System.out.println("齐地风云");		
	}	
}

泛型方法的定义:

格式:public <泛型类型> 返回类型 方法名(泛型类型 )   --------------  前后泛型类型一致

public class GenericDemo01 {
	public static void main(String[] args) {	
		test("");  //java.lang.String
		test(123);  //java.lang.Integer
		test('a');  //java.lang.Character
		test(12.0); //java.lang.Double	
	}	

	//泛型的方法定义:如上所示,可以传入任意类型的对象
	public static <T> void test(T t) {
		System.out.println(t.getClass().getName());
	}
}

泛型通配符的使用:

通配符,类型不确定,用于声明 变量|形参 上
不能用在:
 * 1,创建对象
 * 2,创建泛型类 、泛型方法、泛型接口上

1.  <?> 表示任意类型,如果没有明确,那么就是Object以及任意的Java类型;

2. <? extends E> 向下限定:E及其子类;

3. <? super E> 向上限定,E及其父类。

public class GenericDemo02 {
	public static void main(String[] args) {
		//任意类型,如果没有明确,那么就是Object以及任意的Java类型
		Collection<?> c1 = new ArrayList<Animal>();
		Collection<?> c2 = new ArrayList<Dog>();
		Collection<?> c3 = new ArrayList<Cat>();
		Collection<?> c4 = new ArrayList<Object>();
		
		// ? extends E  ---  向下限定:E及其子类
		Collection<? extends Animal> c5 = new ArrayList<Animal>();
		Collection<? extends Animal> c6 = new ArrayList<Dog>();
		Collection<? extends Animal> c7 = new ArrayList<Cat>();
		//Collection<? extends Animal> c8 = new ArrayList<Object>(); 报错
		
		// ? super E  ---  向上限定,E及其父类
		Collection<? super Animal> c9 = new ArrayList<Animal>();
		//Collection<? super Animal> c10 = new ArrayList<Dog>(); 报错
		//Collection<? super Animal> c11 = new ArrayList<Cat>();
		Collection<? super Animal> c12 = new ArrayList<Object>();
	}
}
class Animal{}
class Dog extends Animal{}
class Cat extends Animal{}

关于泛型继承问题的文章:https://www.cnblogs.com/lihaoyang/p/7104293.html

关于泛型通配符和嵌套的文章:https://www.cnblogs.com/lihaoyang/p/7105581.html

猜你喜欢

转载自blog.csdn.net/AI_drag0n/article/details/85046360
今日推荐