Java(集合)
数组的不足:
集合:
集合的框架:
1. 集合主要是两组(单列集合 , 双列集合)
2. Collection 接口有两个重要的子接口 List Set , 他们的实现子类都是单列集合
3. Map 接口的实现子类 是双列集合,存放的 K-V
Collection接口实现类的特点:
Collection的常用方法:
add():添加单个元素
remove():删除指定元素
contains():查找元素是否存在
size():获取元素个数
isEmpty():判断是否为空
clear():清空
addAll():添加多个元素
containsAll():查找多个元素是否都存在
removeAll():删除多个元素
Collection 接口遍历元素方式:
1.使用 Iterator(迭代器):
如果希望再次遍历,需要重置我们的迭代器
Collection col = new ArrayList();
iterator = col.iterator();
2.for 循环增强
List 接口和常用方法:
索引是从 0 开始的
常用方法:
void add(int index, Object ele):在 index 位置插入 ele 元素
boolean addAll(int index, Collection eles):从 index 位置开始将 eles 中的所有元素添加进来
Object get(int index):获取指定 index 位置的元素
int indexOf(Object obj):返回 obj 在集合中首次出现的位置
int lastIndexOf(Object obj):返回 obj 在当前集合中末次出现的位置
Object remove(int index):移除指定 index 位置的元素,并返回此元素
Object set(int index, Object ele):设置指定 index 位置的元素为 ele , 相当于是替换.
List subList(int fromIndex, int toIndex):返回从 fromIndex 到 toIndex 位置的子集合(fromIndex <= subList < toIndex)
List 的三种遍历方式: