List Interface
1.两个包含相同元素和顺序的List逻辑上是相等的。
2.两种基本实现ArrayList, LinkedList。
3.位置访问。get, set, add, addAll, remove
4.搜索。indexOf, lastIndexOf
5.List Iterator相关 (ListIterator继承了Iterator)
a. 正向迭代
it=list.listIterator(); //default, at the first element
hasNext()
next()
remove() //定义在Iterator Interface中,删除上一次next()调用返回的元素
nextIndex()
b.方向迭代
it=list.listIterator(list.size()); //default, at the last element
hasPrevious()
previous()
remove() //定义在Iterator Interface中,删除上一次previous()调用返回的元素
previousIndex()
使用迭代器实现List.indexOf(E e):
![](https://img.haomeiwen.com/i9066051/6ebd523f421cf8be.png)
c. 除了Iterator提供的remove()之外,ListIterator还提供了两种修改list的操作
· set(E e)覆盖上一次next() or previous()返回的元素
下面这个例子给出了如何使用set()将一个list中的某元素全部替换成另一个元素
![](https://img.haomeiwen.com/i9066051/8e950822fc9c68e9.png)
·add(E e)在当前光标位置插入一个元素
下面这个例子给出了如何使用add()将一个list中的某元素全部替换成另一个list
![](https://img.haomeiwen.com/i9066051/fbb91dbadb0a0f28.png)
6. Range-View Operations
a. subList(int fromIndex, int toIndex)返回的是原list中fromIndex(inclusive)到toIndex(exclusive)的部分。
b.注意Range-View,这个subList的背后还是原本的list。因此原list的变化在subList上都可以体现出来。
c. 所有参数类型是个List的方法都可以使用subList View。如:
a. list.subList(fromIndex, toIndex).clear();
b. int i = list.subList(fromIndex, toIndex).indexOf(o);
c. int j = list.subList(fromIndex, toIndex).lastIndexOf(o);
d. 应该慎重是使用subList,因为在backing list上的增删操作会使得之前应以的subList语义失效。借助subList(作为一种临时对象是实现)来实现对backing list上的范围操作是比较推荐的做法,比如上面的例子。
7.List Algorithms
--sort — sorts a List using a merge sort algorithm, which provides a fast, stable sort. (A stable sort is one that does not reorder equal elements.)
--shuffle — randomly permutes the elements in a List.
--reverse — reverses the order of the elements in a List.
--rotate — rotates all the elements in a List by a specified distance.
--swap — swaps the elements at specified positions in a List.
--replaceAll — replaces all occurrences of one specified value with another.
--fill — overwrites every element in a List with the specified value.
--copy — copies the source List into the destination List.
--binarySearch — searches for an element in an ordered List using the binary search algorithm.
--indexOfSubList — returns the index of the first sublist of one List that is equal to another.
--lastIndexOfSubList — returns the index of the last sublist of one List that is equal to another.
网友评论