喜欢就在评论区扣1支持吧
Collection学习笔记
Collection集合概述
- 是单例集合的顶层接口
- 它提供了更具体的子接口的实现,如set和list.
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 |
集合的使用样例
import java.util.*;
public class Dmeo {
public static void main(String[] args) {
Collection<String> c = new ArrayList<String>();//多态创建集合对象
c.add("hello"); //添加元素到集合
c.add("world"); //添加元素到集合
Iterator<String> it = c.iterator(); //通过集合对象获取迭代器对象
while (it.hasNext()){//通过hasNext ()方法判断是否还有元素
System.out.println(it.next()); //通过next ()方法获取下一个元素
}
}
}