遍歷Java集合(Arraylist,HashSet...)的元素時,可以采用Iterator迭代器來操作
Iterator接口有三個函數,分別是hasNext(),next(),remove()。
今天淺談remove函數的作用
官方解釋為:
Removes from the underlying collection the last element returned by this iterator (optional operation).
This method can be called only once per call to next().
The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.
譯:從底層集合中移除此迭代器返回的最后一個元素(可選操作)。 每次調用next()時,只能調用此方法一次。 如果在迭代正在進行中以除調用此方法之外的任何方式修改基礎集合,則未指定迭代器的行為。
官方說法現在先不研究
舉個例子1:在使用迭代器遍歷集合的過程中,使用集合對象的remove方法刪除數據時,查看迭代器的運行情況。
List<String> all = new ArrayList<String>(); all.add("a"); all.add("b"); all.add("c"); Iterator<String> iterator=all.iterator();//實例化迭代器 while(iterator.hasNext()){ String str=iterator.next();//讀取當前集合數據元素 if("b".equals(str)){ all.remove(str); }else{ System.out.println( str+" "); } } System.out.println("\n刪除\"b\"之后的集合當中的數據為:"+all);
輸出結果為:
發現:使用集合對象 all 的 remove() 方法后,迭代器的結構被破壞了,遍歷停止了。
---------------------------------------------------------------------------------------------------
舉個例子2:在使用迭代器遍歷集合的過程中,使用迭代器的 remove 方法刪除數據時,查看迭代器的運行情況
List<String> all = new ArrayList<String>(); all.add("a"); all.add("b"); all.add("c"); Iterator<String> iterator = all.iterator();//實例化迭代器 while(iterator.hasNext()){ String str=iterator.next();//讀取當前集合數據元素 if("b".equals(str)){ //all.remove(str);//使用集合當中的remove方法對當前迭代器當中的數據元素值進行刪除操作(注:此操作將會破壞整個迭代器結構)使得迭代器在接下來將不會起作用 iterator.remove(); }else{ System.out.println( str+" "); } } System.out.println("\n刪除\"b\"之后的集合當中的數據為:"+all);
運行結果
發現:使用迭代器 的 remove() 方法后,迭代器刪除了當前讀取的元素 “b”,並且繼續往下遍歷元素,達到了在刪除元素時不破壞遍歷的目的。
原文鏈接:https://blog.csdn.net/qq_30310607/article/details/82347807