Collection体系结构:
注:圆形为接口,方形为实现类,
有关ArrayList的知识我曾经写过。
Collection 集合概述
- 是单列集合的顶层接口,它表示一组对象,这些对象也称为 Collection 的元素
- JDK 不提供此接口的如何直接实现,它提供更具体的子接口(如Set和List)实现
创建 Collection 集合的对象
- 多态的方式
- 具体的实现类ArrayList
import java.util.ArrayList;
import java.util.Collection;
public class Demo {
public static void main(String[] args) {
//创建 Collection 集合对象
Collection<String> c = new ArrayList<String>();
//添加元素:add(E e)
c.add("hello");
c.add("world");
//输出
System.out.println(c);
}
}
输出:
[hello, world]
Collection 集合常用方法
方法名 | 说明 |
---|---|
boolean add(E e) | 添加元素 |
boolean remove(Object o) | 从集合中移除指定的元素 |
void clear() | 清空集合中的元素 |
boolean contains(Object o) | 判断集合中是否存在指定的元素 |
boolean isEmpty() | 判断集合是否为空 |
int size() | 集合的长度,也就是集合中元素的个数 |
Collection 集合的遍历
Iterator:迭代器,集合的专用遍历方式
- Iterator iterator():返回此集合中元素的迭代器,通过集合Iterator()方法得到
- 迭代器是通过集合的iterator()方法得到的,所以我们说它是依赖与集合而存在的
Iterator中的常用方法
方法名 | 说明 |
---|---|
E next() | 方法迭代中的下一个元素 |
boolean hasNext() | 如果迭代具有更多元素,则返回true |
例:输出 Helloworld
Collection<String> c = new ArrayList<String>();
c.add("Hello");
c.add("world");
c.add("1314");
Iterator<String> it = c.iterator();
//如果it没有下一个元素,就结束循环
while(it.hasNext()){
String s = it.next();//输出元素,并跳到下一个元素
System.out.println(it.next());
}
输出:
Hello
world
1314
练习
案例:Collection集合存储学生对象并遍历
需求:创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合
定义学生类:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Demo {
public static void main(String[] args) {
//创建Collection集合对象
Collection<Student> c = new ArrayList<Student>();
//创建学生对象
Student s1 = new Student("张三",18);
Student s2 = new Student("李四",19);
Student s3 = new Student("王五",20);
//将学生添加到集合
c.add(s1);
c.add(s2);
c.add(s3);
//遍历集合
Iterator<Student> it = c.iterator();//创建Iterator对象
while(it.hasNext()){
Student s = it.next();
System.out.println(s.getName()+","+s.getAge());
}
}
}
输出:
张三,18
李四,19
王五,20