• 泛型的处理


    来源:由于集合可以存储任意类型的对象,就有肯能在转换的时候出现类型转换异常所以为了解决这个问题提供一种机制,叫做泛型

    泛型:是一种广泛的类型,把明确数据类型的工作提前到了编译时期,借鉴了数组的特点

    泛型好处:

    •   避免了类型转换的问题
    •   可以减少黄色警告线  
    • 可以简化我们代码的书写

    什么时候可以使用泛型: 问API,当我们看到这样<E>

    public class GenericDeom {
        public static void main(String[] args) {
            //创建集合对象
            Collection c =new ArrayList();
            //创建元素对象
            Student s =new Student("zhangsan",18);
            Student s2 =new Student("lisi",19);
            //添加元素对象
            c.add(s);
            c.add(s2);
            //遍历集合对象
            Iterator it =c.iterator();
            while(it.hasNext()) {
                String str =(String)it.next();
                System.out.println(str);
                
                //Student stu=it.next();
                //System.out.println(stu.name);
            }
        }
    Exception in thread "main" java.lang.ClassCastException: com.kundada3.Student cannot be cast to java.lang.String
    	at com.kundada3.GenericDeom.main(GenericDeom.java:35)
    

     原因:添加的是学生,往字符串去转所以出错

    在实例化泛型类时,必须指定E的具体类型

    public class GenericDeom {
        public static void main(String[] args) {
            //创建集合对象
            Collection<Student> c =new ArrayList<Student>();
            //创建元素对象
            Student s =new Student("zhangsan",18);
            Student s2 =new Student("lisi",19);
            //添加元素对象
            c.add(s);
            c.add(s2);
            //遍历集合对象
            Iterator<Student> it =c.iterator();
            while(it.hasNext()) {
                //String str =(String)it.next();
                //System.out.println(str);
                
                Student stu=it.next();
                System.out.println(stu.name);
            }
        }
    
    }
    
    class Student{
        String name;
        int age;
        
        //方便对成员变量的初始化
        public Student(String name,int age) {
            this.name=name;
            this.age=age;
        }
    }
  • 相关阅读:
    实现一个与内容合二为一的ActionBar动画效果
    hdoj 1506&amp;&amp;1505(City Game) dp
    remine chart2安装
    zoom的学习
    海哥:T2C时代的到来了,那么什么叫T2C?
    minhash算法
    动态创建按钮的JS
    socket编程在windows和linux下的区别
    http staus汇总
    MySQL HINT:Straight_JOIN
  • 原文地址:https://www.cnblogs.com/kun19/p/11074911.html
Copyright © 2020-2023  润新知