JavaSE | Collection集合

97 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第9天,点击查看活动详情

(二)Collection

1.集合类体系结构

image-20211230180459711

2.Collection集合概述和使用

Collection集合概述

  • 是单例集合的顶层接口,他表示一组对象,这些对象也称为Collection的元素
  • JDK不提供此接口的任何直接实现,它提供更具体的子接口(如set和List)实现

创建Collection集合的对象

  • 多态的方式
  • 具体的实现类ArrayList

代码演示:

import java.util.ArrayList;
import java.util.Collection;

public class CollectionDemo {
    public static void main(String[] args) {
        //创建Collection集合对象
        Collection<String> c = new ArrayList<>();
        //添加元素:boolean add(E e)
        c.add("hello");
        c.add("world");
        c.add("java");
        //输出集合对象
        System.out.println(c);// [hello, world, java]
    }
}

3.Collection集合常用方法

image-20211230203923509

4.Collection集合的遍历

Iterator:迭代器,集合的专用遍历格式

  • Iterator iterator():返回此集合中元素的迭代器,通过集合的iterator()方法得到
  • 迭代器是通过集合的iterator()方法得到的,所以我们说它是依赖于集合而存在的

Iterator中的常用方法

  • E next():返回迭代中的下一个元素
  • boolean hasNext():如果迭代具有更多元素,则返回true

代码演示:

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class CollectionDemo {
    public static void main(String[] args) {
        //创建Collection集合对象
        Collection<String> c = new ArrayList<>();
        c.add("hello");
        c.add("world");
        c.add("java");
        System.out.println(c);  //[hello, world, java]
        //通过集合的 Iterator<E> iterator()方法获得迭代器对象
        Iterator<String> i = c.iterator();//多态的方式获得对象 (在iterator方法里返回了实现类对象)
        //用while循环遍历集合
        while(i.hasNext()){
            String s = i.next();
            System.out.println(s);
        }
    }
}
/*
public Iterator<E> iterator() {
        return new Itr();
    }

private class Itr implements Iterator<E> {
	......
}
*/

5.集合的使用步骤

image-20211230212316073


6.案例(Collection集合存储学生对象并遍历)

代码实现:

创建学生类(Student):

public class Student {
    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

创建测试类(StudentDemo):

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class StudentDemo {
    public static void main(String[] args) {
        //创建集合对象
        Collection<Student> c = new ArrayList<>();
        //创建三个学生对象
        Student s1 = new Student("学生1",20);
        Student s2 = new Student("学生2",21);
        Student s3 = new Student("学生3",22);
        //将学生对象添加进集合中存储
        c.add(s1);
        c.add(s2);
        c.add(s3);
        //通过集合对象的方法获得迭代器对象
        Iterator<Student> i = c.iterator();
        //遍历集合
        while(i.hasNext()) {
            Student s = i.next();
            System.out.println(s.getName()+", "+s.getAge());
        }
    }
}