Java集合类体系
集合类体系结构图
Collection
public interface Collection< E >
是单例集合的顶层接口,它表示一组对象,这些对象也称为Collection的元素。
JDK不提供此接口的任何直接实现:它提供了更具体的子接口实现,如Set和List。
创建Collection集合的对象
多态的方式
具体的实现类ArrayList
// 创建Collection集合的对象
Collection<String> c = new ArrayList<String>();
Collection集合常用方法
方法名 | 说明 |
---|---|
boolean add(E e) | 添加元素 |
boolean remove(Object o) | 从集合中移除指定元素 |
void clear() | 清空集合中的元素 |
boolean contains(Object o) | 判断集合中是否存在指定的元素 |
boolean isEmpty() | 判断集合是否为空 |
int size() | 集合的长度,也就是集合中元素的个数 |
Collection集合的遍历
Iterator:迭代器,集合专用遍历方式
Iterator< E > iterator():返回此集合中元素的迭代器,通过集合的iterator()方法得到
迭代器是通过集合itertor()方法得到的,所以我们说它是依赖于集合而存在的
Iterator中的常用方法
E next():返回迭代中的下一个元素
boolean hasNext():如果迭代具有更多元素,则返回true
Iterator<String> it = c.iterator();
while (it.hasNext()){
String s = it.next();
System.out.println(s);
}
该文参考黑马程序员刘意老师视频总结笔记