轉自:http://blog.csdn.net/goodbaby728/article/details/10163347
ListIterator接口繼承自Iterator接口,新增了add()等方法。
關于ListIterator的add()方法的作用(接口是沒有方法實現的,但其實現類對于add()方法的實現機制大致相同,姑且這樣說吧),《java核心技術 卷I》里如下表述:
“如果多次調用add方法,將按照提供的次序把元素添加到鏈表中。它們被依次添加到迭代器當前位置之前。”
對于這種說法,很容易引發歧義,當前位置是什么?當前指向的元素,還是游標位置?
帶著這種疑問,我查閱了ListIterator接口的API說明文檔(網址見本文結尾),得到對于add()方法的如下英文描述:
Inserts the specified element into the list (optional Operation). The element is inserted immediately before the element that would be returned by
, if any, and after the element that would be returned by next()
, if any. (If the list contains no elements, the new element becomes the sole element on the list.)PRevious()
該描述就很清晰:的確是把新元素插入由next()所返回的那個元素之前,previous()所返回的元素之后。之所以加之前與之后兩個限定,是為了應對在鏈尾(next返回為空)以及鏈頭(previous返回為空)的特殊情況,如果鏈表為空,則新插入的元素就作為該鏈表的唯一元素。另外,每當插入一個元素以后,迭代器都會后移(向著鏈尾方向)一位。
舉例說明:
[java] view plain copyList<String> name=new LinkedList<String>(); name.add("A"); name.add("B"); name.add("C"); ListIterator<String> iter = name.listIterator(); iter.next(); iter.add("D"); iter.add("E"); for(String nm:name) System.out.println(nm);第4行代碼執行完畢,name鏈表內容如下1A2B3C4(數字只作為占位符,可以忽略,內容為ABC,從鏈頭到鏈尾)
第5行定義迭代器以后,初始迭代器的位置是在數字1,執行第6行next以后,迭代器指向數字2的位置,此時如果再執行next(),返回B,執行previous(),返回A,因此應把D插入AB之間,迭代器順移到DB之間;依次類推,可以插入E。最終輸出結果為:
[java] view plain copyA D E B C下面再簡單看一下remove方法,關于remove方法,API文檔描述如下:
Removes from the list the last element that was returned by
ornext()
(optional operation). This call can only be made once per call to previous()
next
orprevious
. It can be made only if
has not been called after the last call to add(java.lang.Object)
next
or previous
.
簡單解釋一下,要執行remove,首先要找到所需移除的元素,怎樣找?當然是通過next()跟previous()方法,所以remove必須要跟在next()或是previous()之后,而且只能執行一次(一個元素當然只能刪一次,刪多個元素,需要再執行next()或previous())。另外,在執行next()或previous()后還不能先執行了 add()方法。因為,否則add()方法執行以后,迭代器已經移動了,這樣所要刪除的目標元素指向不明,會報”Unknown Source“異常。
所以《java核心技術 卷I》對add和remove方法總結如下:add方法只依賴迭代器的位置(next和previous各返回什么元素),而remove方法依賴于迭代器的狀態(是否執行了next或remove方法)。(紅色是我的備注)
對于Java API文檔,推薦GrepCode,網址如下:
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/ListIterator.java?av=h#ListIterator
這里你能看到類或接口的繼承以及實現結構,同時還能查看實現源碼,很不錯。
新聞熱點
疑難解答