美文网首页
day15-06-集合框架(泛型概述)

day15-06-集合框架(泛型概述)

作者: 姗婷 | 来源:发表于2020-06-23 08:10 被阅读0次

    /*
    泛型:JDK1.5版本以后出现了新特性。用于解决类型安全问题。

    好处:
    1.将运行时期出现的ClassCastException,转移到了编译时期。
    方便于程序员姐姐问题,让运行时问题减少,安全。
    2.避免了强制转换的麻烦

    泛型格式:通过<>来定义要操作的引用数据类型。
    在使用java提供的对象时,什么时候写泛型呢?

    通常在集合框架中很常见。只要见到<>就要泛型。
    其实<>就是用来接收类型的。
    当使用集合时,将集合要存储的数据类型作为参数传递到<>中即可。
    */

    import java.util.*;
    class GenericDemo 
    {
        public static void main(String[] args) 
        {
            //数组在创建时,就定义了指定类型。int[] arr = new int[3];集合也类似和数组一样
            
            ArrayList<String> al = new ArrayList<String>();//定义一个ArrayList容器,容器类型是String类型的元素,泛型
            al.add("abc01");
            al.add("abc0991");
            al.add("abc014");
            
            //al.add(4);//al.add(new Integer(4));//1.5版本以后有自动装箱拆箱动作,自动把4封装成对象
    
            //迭代器也要泛型
            Iterator<String> it = al.iterator();
            while(it.hasNext())
            {
                //打印元素长度,不打印toString,有泛型就不用强转String s =(String)it.next();
                String s = it.next();
                System.out.println(s+":"+s.length());
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:day15-06-集合框架(泛型概述)

          本文链接:https://www.haomeiwen.com/subject/arewxktx.html