Collection的常见方法:
- 添加
boolean add(Object obj)
boolean addAll(Collection coll)
- 删除
boolean remove(object obj)
boolean removeAll(Collection coll)
从原集合中删除和参数集合相同的元素。
void clear()
- 判断
boolean contains(object obj)
boolean containsAll(Colllection coll)
boolean isEmpty()
判断集合中是否有元素。 - 获取
int size()
Iterator iterator()
迭代器。
该对象必须依赖于具体容器,因为每一个容器的数据结构都不同,所以该迭代器对象是在容器中进行内部实现的。
对于使用容器者而言,具体的实现不重要,只要通过容器获取到该实现的迭代器的对象即可,也就是iterator()方法。
Iterator接口是对所有Collection容器进行元素遍历的公共接口。 - 其他
boolean retainAll(Collection coll)
取交集。保留和指定集合相同的元素,而删除不同的元素。和removeAll功能相反。
Object[] toArray()
将集合转成数组。 - 遍历
// 使用Collection中的iterator()方法,获取集合的迭代器对象。
Iterator<E> it = c.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
for(Iterator<E> it = c.iterator(); it.hasNext(); ){
System.out.println(it.next());
}