zoukankan      html  css  js  c++  java
  • java集合遍历三种方式和泛型的通配

    集合定义

    集合,集合是java中提供的一种容器,可以用来存储多个数据。

    特点:数组的长度是固定的。集合的长度是可变的。集合中存储的元素必须是引用类型数据‘

    普通for遍历:

    //案例一
    ArrayList<Person> arr=new ArrayList<Person>();
            arr.add(new Person("张三",19));
            arr.add(new Person("小红帽",20));
            arr.add(new Person("小红帽",23));
            for(int i=0;i<arr.size();i++){
                System.out.println(arr.get(i));
            }

    增强for循环遍历:

      案例二          
        Collection<Integer> arr=new ArrayList<Integer>();
            arr.add(789);
            arr.add(456);
            arr.add(123);
            //增强for循环
            /*for(元素的数据类型 变量 : Collection集合or数组){
            }*/
            for(Integer i:arr){
                System.out.println(i);
            }            

    迭代器遍历:

    //案例三
    //1,创建集合对象。
    Collection<String> coll = new ArrayList<String>();
    coll.add("abc1");
    coll.add("abc2");
    coll.add("abc3");
    coll.add("abc4");
     
    //2.获取容器的迭代器对象。通过iterator方法。
    Iterator it = coll.iterator();
     
    //3,使用具体的迭代器对象获取集合中的元素。参阅迭代器的方法
    while(it.hasNext()){
        System.out.println(it.next());
    }

     Collection接口的基本方法

    Collection接口是集合中的顶层接口,那么它中定义的所有功能子类都可以使用

    创建集合的格式:

    方式1:Collection<元素类型> 变量名 = new ArrayList<元素类型>();

    方式2:Collection 变量名 = new ArrayList();

     集合元素的向下转型

    Collection coll = new ArrayList();
    coll.add("abc");
    coll.add("aabbcc");
    coll.add(1);
    Iterator it = coll.iterator();
    while (it.hasNext()) {
        //由于元素被存放进集合后全部被提升为Object类型
    //当需要使用子类对象特有方法时,需要向下转型
        String str = (String) it.next();
        System.out.println(str.length());
    }

    泛型和通配符

      类定义格式:修饰符 class 类名<代表泛型的变量> { }

      接口定义格式:修饰符 interface接口名<代表泛型的变量> { }

    限定泛型的下限:

    //? extends Person  限定泛型的上限
        //? super Person     限定泛型的下限
        public static void get(Collection<? extends Person> c){
            Iterator<?> it=c.iterator();
            while(it.hasNext()){
                //向下转型
                Object obj=it.next();
                Person p=(Person)obj;
                System.out.println(p.getName());
            }
  • 相关阅读:
    头条前端笔试最后一道题
    Node读取和写入json,格式化输出json
    CSS中的未定义行为,浏览器的差异(一)
    18.2.28阿里前端实习生内推面补坑
    18.2.26深信服Web实习生补坑(已拿到offer)
    MySQL Parameter '?…' has already been defined 是什么问题
    C# List<T>的 Find方法、FindLast方法、FindAll方法、FindIndex方法
    C# 对List<T>进行排序
    SQL里 asc和desc的意思
    Visual Studio同步的时候显示 team foundation 错误 系统找不到指定文件夹
  • 原文地址:https://www.cnblogs.com/haoduoyu0512/p/13297885.html
Copyright © 2011-2022 走看看