java中泛型的学习

泛型的引入:

需求:ArrayList集合存储元素并遍历

  问题:使用ArrayList集合存储元素遍历的时候,按照正常的操作出现了问题,
  当前ArrayList集合中存储了两种类型的元素分别String和Integer类型,在遍历的时候,
           使用的是String接收的,对于Integer类型就出现了异常!
 回想数组:
  String[] str = new String[3] ;
  str[0] = "hello" ;
  str[1] = "world" ;
  str[2] = 100 ; 错误的,
 数组直接定义了存储的类型,防止出现其他类型的元素,集合能不能也像数组一样, 针对这种情况引出一种技术: 泛型
          <数据类型> --- 引用数据类型
  泛型:将明确的集合类型的工作推迟到了创建对象或者调用方法的时候,属于一种参数化类型,可以作为参数传递.
  泛型的好处:
  1)将运行时期异常提前到了编译时期
2)优化了设计,解决了黄色警告线问题
  3)避免了强制类型转换

 注释:泛型的引出可以提供程序的安全性!

举例:

 * @author 田伟
 *
 */
public class ArrayListDemo1 {
public static void main(String[] args) {
	ArrayList<String> arr=new ArrayList<String>();
	arr.add("hello");
	arr.add("world");
	arr.add("java");
    Iterator<String> it=arr.iterator();
    while(it.hasNext()) {
    	String s=it.next();
    	System.out.println(s);
    }
}
}

使用ArrayList集合存储自定义对象并遍历,加入泛型

举例:

 * @author 田伟
 *
 */
public class ArrayListDemo2 {
public static void main(String[] args) {
	ArrayList<Student> arr=new ArrayList<Student>();
	Student s1=new Student("貂蝉 ",28);
	Student s2=new Student("孙尚香 ",20);
	Student s3=new Student("花木兰 ",18);
	Student s4=new Student("武则天 ",50);
	arr.add(s1);
	arr.add(s2);
	arr.add(s3);
	arr.add(s4);
	Iterator<Student> it =arr.iterator();
	while(it.hasNext()) {
		Student s=it.next();
		System.out.println(s);
	}
	System.out.println("------------");
	for(int i=0;i<arr.size();i++) {
		Student s=arr.get(i);
		System.out.println(s);
	}
	
}
}
泛型高级(通配符)
 <?>  :代表任意类型Object类型,或者任意的Java类 
 <? extends E>:向下限定,E的子类或者E这个类型

 <? super E>:向上限定,E及其他的父类

范式的基本格式:

//创建集合对象,泛型如果明确的情况下,前后必须保持一致

Collection<Object> c1 = new ArrayList<Object>() ;
Collection<Object> c2 = new ArrayList<Cat>() ;
Collection<Object> c3 = new ArrayList<Animal>() ;
<?>  :代表任意类型Object类型,或者任意的Java类 
Collection<?> c4 = new ArrayList<Object>() ;
Collection<?> c5 = new ArrayList<Animal>() ;
Collection<?> c6 = new ArrayList<Dog>() ;
Collection<?> c7= new ArrayList<Cat>() ;
<? extends E>:向下限定,E的子类或者E这个类型
Collection<? extends Object> c8 = new ArrayList<Object>() ;
Collection<? extends Object> c9 = new ArrayList<Animal>() ;
Collection<? extends Object> c10 = new ArrayList<Cat>() ;
Collection<? extends Aninal> c11 = new ArrayList<Object>() ;
<? super E>:向上限定,E及其他的父类
Collection<? super Animal> c12 = new ArrayList<Cat>() ;
Collection<? super Animal> c13 = new ArrayList<Animal>() ;
Collection<? super Animal> c14 = new ArrayList<Object>() ;

猜你喜欢

转载自blog.csdn.net/wt5264/article/details/80258360