List中的迭代器
List操作中最常见莫过于 增删改查四个功能。在学习了迭代器后,我们能够更方便的实现增删改查这四个功能,话不多说,直接上代码。
public class ListIteratorDemo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("hello world1");
list.add("hello world2");
list.add("hello world3");
list.add("hello world4");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
Object obj = iterator.next();
if (obj.equals("hello world2")) {
// 此处会发生并发的异常
list.add("java008");
System.out.println(obj);
}
}
}
}
很简单的遍历容器后,判断是否存在“hello world2”,然后添加一个“java008”进入容器。运行程序却抛出异常“ConcurrentModificationException”,查询发现是一个并发的问题。一边操作迭代器,一边使用容器的方法添加造成的并发异常。
看来如果要使用迭代器的话,只能使用迭代器来操作容器的元素。查询api发现迭代器只有三个方法:hasNext(), next(), remove()。 接着发现了一个ListIterator继承了Itertor,查询方法发现了这个简直是加强版的迭代器。
Modifier and Type Method and Description
void add(E e)
Inserts the specified element into the list (optional operation).
boolean hasNext()
Returns true if this list iterator has more elements when traversing the list in the forward direction.
boolean hasPrevious()
Returns true if this list iterator has more elements when traversing the list in the reverse direction.
E next()
Returns the next element in the list and advances the cursor position.
int nextIndex()
Returns the index of the element that would be returned by a subsequent call to next().
E previous()
Returns the previous element in the list and moves the cursor position backwards.
int previousIndex()
Returns the index of the element that would be returned by a subsequent call to previous().
void remove()
Removes from the list the last element that was returned by next() or previous() (optional operation).
void set(E e)
Replaces the last element returned by next() or previous() with the specified element (optional operation).
使用ListIterator
public class ListIteratorDemo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("hello world1");
list.add("hello world2");
list.add("hello world3");
list.add("hello world4");
ListIterator<String> iterator = list.listIterator();
while (iterator.hasNext()) {
Object obj = iterator.next();
if (obj.equals("hello world2")) {
// 此处会发生并发的异常
iterator.add("hello");
}
}
System.out.println(list);
}
}
List小结
大概了解List后,发现其实List更像封装的数组。List都是带有角标的,如果有学过数据结构,会发现迭代器的操作更像是封装好的增删改查功能。大神写的代码肯定不比我们略懂皮毛数据结构的菜鸟,研究过数据结构的链表会发现LinkedList其实就是链表。而ArrayList就是顺序表。容器类在JDK中都是放在util工具类中,JAVA的大神们早就已经把经典数据结构封装好放在容器中,我们在以后的开发中直接用轮子就行了。