泛型

泛型


概念

在编译时期就确定的类型的一种技术。
泛型是一种参数化类型。
泛型是JDK1.5之后引入的新特性,是一种将引用类型当做参数传递的参数化类型,在编译时期就已经确定了集合存储的元素类型。


格式

<数据类型> 这里的类型必须是引用类型
泛型一般用于集合

泛型的好处:
1.提高了程序的安全性。
2.消除了黄色警告线。
3.在编译时期将类型确定,减少不必要的强转代码。


应用

泛型根据放置的位置不同分为:

  • 泛型类
  • 泛型方法
  • 泛型接口
泛型类
public class GenericDemo02 {
	public static void main(String[] args) {
		// 没有学习泛型之前
//		GenericClass gc = new GenericClass();
//		gc.setObj(10);
//		gc.setObj("张三");
//		
//		System.out.println(gc.getObj());
		
		// JDK5.0之后引入了泛型
		GenericClass<String> gc = new GenericClass<String>();
		gc.setObj("张三");
		gc.setObj("李四");
		
		System.out.println(gc.getObj());
	}
}

泛型方法
class GenericMethod<E,H,T>{
	private E e;
	
	public void setObj(E e) {
		this.e = e;
	}
	
	public E getObj() {
		return this.e;
	}
	
	public <T> void method(T t) {
		System.out.println(t);
	}
	
	public void show(H h) {
		System.out.println(h);
	}
}

泛型接口
class GenericInterfaceImpl<E> implements GenericInterface<String>{

	@Override
	public void show(String e) {
		System.out.println(e);
	}

	@Override
	public String method() {
		return "method";
	}
	
}

interface GenericInterface<E>{
	
	public abstract void show(E e);
	
	public E method();
}


泛型通配符

  • <?>: 表示任意类型
  • <? extends E> : 向下限定符 E或者E的子类
  • <? super E> : 向上限定符 E或者E的父类
boolean addAll(Collection<? extends E> c) 

以上

@Fzxey

posted @ 2019-04-30 20:29  西江逐月  阅读(305)  评论(0编辑  收藏  举报