java源码分析之LinkedList(六)

2014-11-24 11:27:30 · 作者: · 浏览: 25
ove(lastReturned);
76 } catch (NoSuchElementException e) {
77 throw new IllegalStateException();
78 }
79 if (next==lastReturned)
80 next = lastNext;
81 else
82 nextIndex--;
83 lastReturned = header;
84 expectedModCount++;
85 }
86 // 修改当前节点的内容
87 public void set(E e) {
88 if (lastReturned == header)
89 throw new IllegalStateException();
90 checkForComodification();
91 lastReturned.element = e;
92 }
93 // 在当前持有节点后面插入新节点
94 public void add(E e) {
95 checkForComodification();
96 // 将最近一次返回节点修改为header
97 lastReturned = header;
98 addBefore(e, next);
99 nextIndex++;
100 expectedModCount++;
101 }
102 // 判断expectedModCount和modCount是否一致,以确保通过ListItr的修改操作正确的反映在LinkedList中
103 final void checkForComodification() {
104 if (modCount != expectedModCount)
105 throw new ConcurrentModificationException();
106 }
107 }
下面是一个ListItr的使用实例。
1 LinkedList list = new LinkedList();
2 list.add("First");
3 list.add("Second");
4 list.add("Thrid");
5 System.out.println(list);
6 ListIterator itr = list.listIterator();
7 while (itr.hasNext()) {
8 System.out.println(itr.next());
9 }
10 try {
11 System.out.println(itr.next());// throw Exception
12 } catch (Exception e) {
13 // TODO: handle exception
14 }
15 itr = list.listIterator();
16 System.out.println(list);
17 System.out.println(itr.next());
18 itr.add("new node1");
19 System.out.println(list);
20 itr.add("new node2");
21 System.out.println(list);
22 System.out.println(itr.next());
23 itr.set("modify node");
24 System.out.println(list);
25 itr.remove();
26 System.out.println(list);
1 结果:
2 [First, Second, Thrid]
3 First
4 Second
5 Thrid
6 [First, Second, Thrid]
7 First
8 [First, new node1, Second, Thrid]
9 [First, new node1, new node2, Second, Thrid]
10 Second
11 [First, new node1, new node2, modify node, Thrid]
12 [First, new node1, new node2, Thrid]
LinkedList还有一个提供Iterator的方法:descendingIterator()。该方法返回一个DescendingIterator对象。DescendingIterator是LinkedList的一个内部类。
1 public Iterator descendingIterator() {
2 return new DescendingIterator();
3 }
下面分析详细分析DescendingIterator类。
1 private class DescendingIterator implements Iterator {
2 // 获取ListItr对象
3 final ListItr itr = new ListItr(size());
4 // hasNext其实是调用了itr的hasPrevious方法
5 public boolean hasNext() {
6 return itr.hasPrevious();
7 }
8 // next()其实是调用了itr的previous方法
9 public E next() {
10 return itr.previous();
11 }
12 public void remove() {
13 itr.remove();
14 }
15 }
从类名和上面的代码可以看出这是一个反向的Iterator,代码很简单,都是调用的ListItr类中的方法。