前言
Java的ArrayList学习笔记
继承结构
graph TD
Object --> AbstractCollection
AbstractCollection --> AbstractList
AbstractList --> ArrayList
Iterable --> Collection
Collection --> List
List --> ArrayList
style Object fill:#f0f8ff,stroke:#696969
style AbstractCollection fill:#f0f8ff,stroke:#696969
style AbstractList fill:#f0f8ff,stroke:#696969
style ArrayList fill:#f0f8ff,stroke:#696969
style Iterable fill:#f0f8ff,stroke:#4169e1
style Collection fill:#f0f8ff,stroke:#4169e1
style List fill:#f0f8ff,stroke:#4169e1
创建对象
1
| ArrayList list = new ArrayList();
|
指定底层数组初始长度
1
| ArrayList list = new ArrayList(<index>);
|
基于已有集合创建
1 2 3
| Collection c;
ArrayList list = new ArrayList(c);
|
Collection的相关方法
添加元素
尾部添加元素
1
| boolean success = list.add(<value>);
|
删除元素
删除指定元素
1
| boolean success = list.remove(<value>);
|
条件删除
1 2 3
| boolean success = list.removeIf((item) -> { return true; });
|
删除所有元素
获取长度
1
| int length = list.size();
|
集合判断
判断集合是否为空
1
| boolean result = list.isEmpty();
|
判断是否包含指定元素
1
| boolean exist = list.contains(<value>);
|
集合运算
求并集
- 向尾部插入所有元素
- 如果集合发生改变,则返回true
1 2 3
| Collection c = new ArrayList();
boolean success = list.addAll(c);
|
求差集
1 2 3
| Collection c = new ArrayList();
boolean success = list.removeAll(c);
|
求交集
1 2 3
| Collection c = new ArrayList();
boolean success = list.retainAll(c);
|
子集判断
1 2 3
| Collection c = new ArrayList();
boolean exist = list.containsAll(c);
|
List的相关方法
添加元素
添加元素到指定下标
1
| list.add(<index>, <value>);
|
删除元素
删除指定下标的元素
1
| Object item = list.remove(<index>);
|
修改元素
修改指定下标元素
1
| Object item = list.set(<index>, <value>);
|
获取元素
获取指定下标元素
1
| Object item = list.get(<index>);
|
搜索元素
从头部搜索指定元素
1
| int index = list.indexOf(<value>);
|
从尾部搜索指定元素
1
| int index = list.lastIndexOf(<value>);
|
集合运算
求并集
1 2 3
| Collection c = new ArrayList();
boolean success = list.addAll(<index>, c);
|
集合遍历
通过迭代器遍历集合
1 2 3 4 5
| Iterator iterator = list.iterator(); while (iterator.hasNext()) { Object item = iterator.next(); System.out.println(item); }
|
1 2 3 4 5 6 7 8 9
| ListIterator listIterator = list.listIterator(); while (listIterator.hasNext()) { Object item = listIterator.next(); System.out.println(item); } while (listIterator.hasPrevious()) { Object item = listIterator.previous(); System.out.println(item); }
|
通过for…each语法遍历
1 2 3
| for (Object item : list) { ... }
|
通过forEach方法遍历
forEach()内传入的Lambda表达式内不能访问非final修饰的变量,类属性或实例属性无限制
- 如果变量没有显式通过
final修饰,但是在Lambda表达式内被访问,则Java会为变量隐式添加final修饰
1 2 3
| list.forEach((item) -> { ... });
|
通过下标遍历集合
1 2 3
| for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); }
|
List集合与数组转换
List集合转换为数组
转换为Object类型的数组
1
| Object[] arr = list.toArray();
|
转换为指定类型的数组
1
| Object[] arr = list.toArray(new Integer[0]);
|
数组转换为List集合
asList()得到的集合是只读的,需要再通过new ArrayList<>()创建一个可写的集合
1 2 3
| int[] arr = new int[10];
List<Object> list = new ArrayList<>(Arrays.asList(arr));
|
完成