线性表的增删查改
顺序表中一定要区分两个概念 容量(capacity) vs 元素个数(size);线性表的所有下标只和元素个数相关,和容量无关。
线性结构
*** 特点**:
-
- 元素和元素之间有前后关系
-
- 元素会有在第几个位置的概念,位置通过下标(index)表示,从 0 开始
-
- 插入可以根据位置的不同,分为:头插、尾插、按位置插入
-
- 删除可以根据位置的不同,分为:头删、尾删、按位置删除
-
- 遍历可以分为从前往后遍历和从后往前遍历
-
- Java 中,List 是一个接口,并且是 Collection 的子接口
线性表的增删查改
尾插
- 将 e 尾插到线性表中
- 返回值 一定是 true,表示插入成功。线性表是不会出现插入不成功的情况的
boolean add(元素类型 e);
插入指定位置
- 将 e 插入到线性表的 index 位置处;要求原来 index 及之后的元素全部向后移动
- index 的可选范围是 0 <= index <= size()
void add(int index, 元素类型 e);
删除指定位置元素
- 删除 index 位置的元素,并返回该元素;要求 原来 index + 1 及之后元素全部向前移动
- index 的可选范围是 0 <= index < size()
元素类型 remove(int index);
遍历删除指定元素
- 删除从前往后遍历时,遇到的第一个相等的(equals)元素
- 返回值 true:删除成功; false:没有找到相等的元素
boolean remove(元素类型 e);
返回 index 位置的元素
- index 的可选范围是 0 <= index < size()
- 返回值 获取到的元素
元素类型 get(int index);
替换 index 位置的元素
- 用新的元素 e 替换 index 位置的元素,并返回 index 位置的原来的元素
- index 的可选范围是 0 <= index < size()
元素类型 set(int index, 元素类型 e);
判断与元素 e 相等
- 通过遍历的方式,判断与元素 e 相等(equals)的元素是否存在于线性表中
- 返回 true:包含;false:不包含
boolean contains(元素类型 e);
遍历判断与元素 e是否相等
- 按照从前往后遍历的方式,找到第一个与元素 e 相等(equals)的元素的下标
- return >= 0 表示找到并且返回下标;-1 代表没有找到
int indexOf(元素类型 e);
- 按照从后往前遍历的方式,找到第一个与元素 e 相等(equals)的元素的下标
- return >= 0 表示找到并且返回下标;-1 代表没有找到
int lastIndexOf(元素类型 e);
清空线性表
- 清空线性表,也就是,调用 clear() 后,线性表的 size() == 0;isEmpty() ==
true
void clear();
返回线性表中已有元素的个数
- return 返回元数个数
int size();
返回线性表是不是一个空的容器
- return true 为空容器
boolean isEmpty();
其他方法
Iterator iterator();
void sort(Comparator 比较器);
List subList(int fromIndex, int toIndex);
boolean addAll(Collection 集合);
boolean addAll(int index, Collection 集合);
boolean containsAll(Collection 集合);
boolean removeAll(Collection 集合);
boolean retainAll(Collection 集合);
Object[] toArray();