java集合中Collection接口和List接口的遍历方式

一、Collection接口的遍历方式

  1. 增强for遍历
  2. 迭代器Iterator遍历
Collection<Student> collection = new ArrayList<Student>();
        Student stu1 = new Student("张三", "男");
        Student stu2 = new Student("李四", "男");
        Student stu3 = new Student("王五", "男");
        Student stu4 = new Student("赵六", "男");
        Student stu5 = new Student("王丽", "女");
        Student stu6 = new Student("王丽", "女");
        // 添加
        collection.add(stu1);
        collection.add(stu2);
        collection.add(stu3);
        collection.add(stu4);
        collection.add(stu5);
        collection.add(stu6);
        System.out.println(collection);
        System.out.println(collection.size());
        //删除
        collection.remove(new Student("王丽", "女"));
        System.out.println(collection.size());
        //遍历
        // 1.foreach
        for (Student student : collection) {
            System.out.println(student);
        }
        System.out.println("-----------------------");
        // 2. iterator
        Iterator<Student> iterator = collection.iterator();
        while(iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        //判断包含
        System.out.println(collection.contains(stu1));
        //如果要让判断new的名字和性别都相同的对象为同一个对象,可以在Student类中重写Object类的equals方法

二、List接口的遍历方式

  1. ArrayList接口
    1. 增强for遍历
    2. 普通for循环
    3. 迭代器Iterator遍历
    4. 列表迭代器ListIterator遍历
    ArrayList<String> arrayList = new ArrayList<>();

        // 添加
        arrayList.add("苹果");
        arrayList.add("西瓜");
        arrayList.add("橙子");
        arrayList.add("香蕉");
        arrayList.add("柠檬");
        // 删除
        // arrayList.remove(new String("苹果"));
            System.out.println(arrayList);

        // 遍历
        // 1.for
        for (int i = 0; i < arrayList.size(); i++) {
            System.out.println(arrayList.get(i));
        }
        System.out.println("--------------------------");
        // 2.foreach
        for (String string : arrayList) {
            System.out.println(string);
        }
        System.out.println("---------------------------");
        // 3.Iterator
        Iterator<String> iterator = arrayList.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        System.out.println("----------------------------");
        // 4.ListIterator
        ListIterator<String> listIterator = arrayList.listIterator();
        while (listIterator.hasNext()) {
            System.out.println(listIterator.next());
        }
        System.out.println("----------------------------------");
        while (listIterator.hasPrevious()) {
            System.out.println(listIterator.previous());
        }
        // 包含
        System.out.println(arrayList.contains("苹果"));
        System.out.println(arrayList.contains(new String("苹果")));
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页