目录
前言
一、Iterable
二、Collection
三、List
前言
一、Iterable
Iterable:具备迭代能力的泛型接口,只要实现了该接口的所有对象,那么就会具备迭代能力。他的成员方法如下:
| 方法 | 描述 |
| iterator() | 返回一个内部元素为T类型的迭代器 |
| forEach() | 对内部元素进行遍历 |
举例实现:
public class Demo {
public static void main(String[] args) {
Collection list = new HashSet<>(Arrays.asList(1, 5, 2, 7, 3, 9));
// x 指向了迭代器对象
Iterator x = list.iterator();
while (x.hasNext()) { // x.hasNext() 元素的个数 + 1
System.out.println(x.next()); // x.next() 元素的个数
}
}
}
二、Collection
Collection是一个继承了Iterable接口的接口,故而所有Collection都具备迭代器功能。它的一般方法如下:
| 方法 | 描述 |
| int size() | 返回容器中的元素个数 |
| boolean isEmpty() | 判断容器是不是空的。注意:容器是empty和容器是null不相等 |
| boolean contains(Object o) | 容器中存在元素 o,需要遍历容器中所有元素,和o进行相等性比较 |
| boolean add(E e) | 把元素 e 放入容器中 |
| boolean remove(Object o) | 将容器中与 o 相等的一个元素删除掉 |
| boolean addAll(Collection c) | 将 c 容器中的所有元素都放到当前容器中 |
| void clear() | 清空容器中的所有元素 |
三、List
List是一种线性结构,元素有顺序
可进行头插、尾插、头删、尾删、排序等操作
List具有迭代的能力
List是一种线性结构,元素有顺序
可进行头插、尾插、头删、尾删、排序等操作
List具有迭代的能力
常见方法:
| 方法 | 描述 |
| boolean add(E e) | 把元素 e 放入 List,用的是尾插操作 |
| void add(int index, E element) | 将元素插入指定的 index 位置 |
| boolean remove(Object o) | 删除第一个遇到的和 o 相等的元素 |
| E remove(int index) | 将[index]位置的元素取出并返回 |
| boolean addAll(Collection c) | 将 c 容器中的所有元素按照次序一个一个的尾插到当前 this 容器中 |
| void sort(Comparator< E > c) | 以 c 作为元素的比较器,对元素进行原地排序 |
| E get(int index) | 返回 index 下标的元素 |
| E set(int index, E element) | 用 element 替换 index 位置的元素,并返回 index 位置原来的元素 |
| int inedxOf(E e) | 从前往后找,第一个和 e 相等的元素的位置 |
| int lastIndexOf(E e) | 从后往前,最后一个和 e 相等的元素所在的位置 |
| List< E > subList(int fromIndex, int toIndex) | 将原有线性结构的[fromIndex, toIndex)截取成一个新的线性结构并返回 |



