----------- android培训、java培训、期待与您交流! ------------
(1)JDk1.5版本以后出现的新特性,用于解决安全问题,是一个安全机制。
好处
1. 将运行时期出现问题ClassCastExpcetion,转移到了编译时期,
方便于程序员解决问题。让运行事情问题减少,安全。
2. 避免了强制转换的麻烦。
3. 泛型格式:通过<>来定义要操作的引用数据类型。
当使用集合时,将集合中要存储的数据类型作为参数传递到<>中即可。
public class GenericTest {
public static void main(String[] args) throws Exception{
ArrayList<String> collection1 = new ArrayList<String>();
collection1.add("abc");
String element = collection1.get(0);
ArrayList<Integer> collection2 = new ArrayList<Integer>();
collection2.getClass().getMethod("add", Object.class).invoke(collection2, "asd");
System.out.println(collection2.get(0));
}
}
泛型的基本了解:
A,参数化类型与原始类型的兼容性:
参数化类型可以引用一个原始类型的对像,编译报告警告,例如:
Collection<String> c = new Vector();
原始类型可以引用一个参数化类型的对象,编译报告警告,例如:
Collection c = new Vector<String>();
B,参数化类型不考虑类型参数的继承关系:
Vector<String> v = new Vector<Object>(); //错误
Vector<Object> v = new Vector<Stringt>(); //错误
C,在创建数组实例时,数组的元素不能使用参数化的类型。
问题:定义一个方法,该方法用于打印出任意参数化类型的集合中的所有数据。
public static void printCollection(Collection<?> cols) {
for(Object obj : cols){
System.out.println(obj);
}
cols.add(“String”); //错误,因为不知道自己匹配就是一定是String
cols.size(); //此方法与类型参数没有关系
cols = new HashSet<Date>();
}
通配符?
使用?通配符可以引用其他各种参数化的类型,?通配符定义的变量主要用作引用,可以调用与参数无关的方法,不能调用与参数有关的方法。
泛型的限定:
? extends E:可以接收E类型或者E的子类型。上限。
? super E:可以接收E类型或者E的父类型。下限。
A限定通配符的上界:
Vector<? Extends Number> x = new Vector<Integer>(); //?表示匹配任意类型。限定类型,仅限于Number及Number的子类,Integer是Number的子类
B限定通配符的下界:
Vector<? super Integer> x = new Vector<Number>();//Number是Integer的父类
class GenericDemo2{
public static void main(String[] args){
ArrayList<String> al = new ArrayList<String>();
al.add(“a”);
al.add(“b”);
ArrayList<Integer> all = new ArrayList< Integer >();
al.add(“12”);
al.add(“34”);
printCol(al);
printCol(all);
}
public static void printcol(ArrayList<?> al){
Iterator<?> it = al.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
(2)自定义泛型
泛型方法的声明应在返回值前紧挨着的位置。
public static <T> T add(T x,T y){
return null;
}
add(3,5);
add(3.5,2); //返回的是类型的交集 Number类型
add(3, “avc”); // 返回的是类型的交集
(3)定义泛型类型
如果累的实例对象中的多处都要用到同一个泛型参数,即引用的泛型类型要保持同一个实际类型时,这时候就要采用泛型类型的方法进行定义,也就是类级别的泛型,语法格式:
public class GenericDao<T>{
private T field1;
public void save(T obj){}
public T getByld(int id){}
}
类级别的泛型是根据引用该类名时指定的类型信息来参数化类型变量的,如下两种方式都可以:
GenericDao<String> dao = null;
New genericDao<String>();
例如:
Class Demo<T>{
public void show(T t){
System.out.println(“show:”+t);
}
public void print(T t){
System.out.println(“print:”+t);
}
}
class GenericDemo{
public static void main(String[] args){
Demo<String> d = new Demo<String>();
d.show(“heima”);
d.print(“heima”);
}
}
注意:
在对泛型类型进行参数化时,类型参数的实例必须是引用类型,不能是基本类型。
当一个变量被声明为泛型时,只能被实例变量和方法调用,而不能被静态变量和静态方法调用。因为静态成员是被所有参数化的类型所共享的,所以静态成员不应该有类级别的类型参数。
----------------------- android培训、java培训、java学习型技术博客、期待与您交流! ----------------------