实例化:
List<String> list = new ArrayList<String>();
Map<Object, Object> map = new HashMap<Object, Object>();
泛型让变编译器做类型安全检查,运行时候类型就被确定,此时泛型会被去除泛型只可以写基本数据类型
接下来可以看看自定义泛型:自定义泛型可以用一个E来表示泛型的元素,在实例化时候,泛型前后必须一致
声明泛型Test<Long>和Test<Integer>是两个是不一样的类型,所以需要一致,Test<Long> f = new Test<Integer>();这样是不行的,但是可以这样Test<Long> f = new Test<>();不过需要jdk1.7之后可以这样用
public class Test<E> {
public void add(E e){
}
public static void main(String[] args) {
Test<String> f = new Test<String>();
//实例化的时候泛型前后需要一致,
//例如Test<Long> f = new Test<Integer>();这样是不行的
//但是可以这样Test<Long> f = new Test<>();不过需要jdk1.7之后可以这样用
//Test<Long>和Test<Integer>是两个是不一样的类型
f.add("ee");
}
}
泛型的继承:下面的类的泛型类型只能是Number或者Number的子类型,所以Long,Integer,Double都可以作为泛型的类型,但是String,char等等就不可以了
//此时泛型只能是Number子类类型
public class Point<T extends Number>{
public static void main(String[] args) {
Point<Long> p = new Point<Long>();
Point<Integer> p1 = new Point<Integer>();
Point<Double> p2 = new Point<Double>();
//Point<String> p2 = new Point<String>();
//String不是Number的子类所以错误
}
}
泛型的通配符:T表示泛型,定义泛型变量private T x; 此时泛型类可以使任意一种简单数据类型,
下列代码有用到通配符Point<?> 代表可以传入任意数据类型,Point<? extends Number>代表只要是Number或者Number的子类就可以,而Point<? super Double> 代码必须是Double或者Double的父类(比如Number)才可以,需要注意的是extends可以在写自定义类的泛型上,而super是不可以。
public class Point<T>{
//参数的定义
private T x;
private T y;
public static void main(String[] args) {
Point<Long> p = new Point<Long>();
Point<Integer> p1 = new Point<Integer>();
Point<Double> p2 = new Point<Double>();
}
//通配符
//可以处理所有Point泛型的类型
public void draw(Point<?> p){
}
//只能传Number或者Number子类
//extends可以写到自定义类上面
public void draw1(Point<? extends Number> p){
}
//只能传Double或者Double父类
//super不能写到自定义类上面
public void draw3(Point<? super Double> p){
}
}
方法的泛型:多用于接口的使用,不是用的对数据进行操作,这个方法可以传入任意数据,进行返回,通常可以接口实现
public <T> T Test1(T t){
return t;
}
接口实现:定义接口,写泛型方法,此方法的功能是传入一个任意类型Class,返回一个实例化对象
这里使用到了反射传入任意数据类型的如s.getClass(); 通过newInstance()方法创建一个对象返回
public interface Test2 {
public <T> T getObject(Class<T> ass);
}
public class Test2Impl implements Test2{
public <T> T getObject(Class<T> ass){
// TODO Auto-generated method stub
try {
return ass.newInstance();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public static void main(String args[]){
Test2Impl t = new Test2Impl();
String s = t.getObject(s.getClass());
}
}