搜尋
首頁Javajava教程java中關於Iterator介面和LIstIterator介面的具體介紹

這篇文章主要介紹了java  Iterator介面LIstIterator介面分析的相關資料,需要的朋友可以參考下

#java  Iterator介面和LIstIterator介面分析

#目錄

1.Iterator介面
2.ListIterator
3.Iterator和ListIterator的區別 

正文

在繼續看ArrayList源碼之前,先了解Iterator接口和ListIterator接口,下篇文章詳細講解ArrayList是如何實現它們的。

我們知道,介面只是一種規範,當繼承介面並實作其中的方法時,要遵循介面對方法的說明。

1.Iterator介面

Iterator介面取代了Java集合框架中的Enumeratrion。 Iterators不同於enumerations的地方主要有兩點:

  Iterators允許呼叫者在迭代過程中從集合中移除元素;

  方法名稱得到了改善。

Iterator原始碼如下:

/**
 * An iterator over a collection. {@code Iterator} takes the place of
 * {@link Enumeration} in the Java Collections Framework. Iterators
 * differ from enumerations in two ways:
 * Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
 * Method names have been improved.
 * This interface is a member of the Java Collections Framework.
 * @param <E> the type of elements returned by this iterator*/
public interface Iterator<E> {
  /**
   * Returns {@code true} if the iteration has more elements.
   * (In other words, returns {@code true} if {@link #next} would
   * return an element rather than throwing an exception.)
   * @return {@code true} if the iteration has more elements
   */
  boolean hasNext();

  /**
   * Returns the next element in the iteration.
   * @return the next element in the iteration
   * @throws NoSuchElementException if the iteration has no more elements
   */
  E next();

  /**
   * Removes from the underlying collection the last element returned
   * by this iterator (optional operation). This method can be called
   * only once per call to {@link #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.
   *
   * @implSpec
   * The default implementation throws an instance of
   * {@link UnsupportedOperationException} and performs no other action.
   *
   * @throws UnsupportedOperationException if the {@code remove}
   *     operation is not supported by this iterator
   *
   * @throws IllegalStateException if the {@code next} method has not
   *     yet been called, or the {@code remove} method has already
   *     been called after the last call to the {@code next}
   *     method
   */
  default void remove() {
    throw new UnsupportedOperationException("remove");
  }

  /**
   * Performs the given action for each remaining element until all elements
   * have been processed or the action throws an exception. Actions are
   * performed in the order of iteration, if that order is specified.
   * Exceptions thrown by the action are relayed to the caller.
   *
   * @implSpec
   * <p>The default implementation behaves as if:
   * <pre class="brush:php;toolbar:false">{@code
   *   while (hasNext())
   *     action.accept(next());
   * }
   *    * @param action The action to be performed for each element    * @throws NullPointerException if the specified action is null    * @since 1.8    */   default void forEachRemaining(Consumer super E> action) {     Objects.requireNonNull(action);     while (hasNext())       action.accept(next());   } }

Iterator介面定義了四個方法以及各個方法的功能,如果有類別實作了這個接口,且實作了這些方法,這個方法需要實作定義的功能,遵循這些規則:

  1).hasNext() 判斷容器是否有下一個元素,有則傳回true;

  2).next() 返回容器中的下一個元素;

  3).remove() 移除目前迭代器傳回的最後一個元素。這個方法在每次呼叫next()方法之後只能呼叫一次;

  4).Java 8 增加forEachRemaining方法,它可以實作對餘下的所有元素執行指定的操作。

更詳細的說明請閱讀原始碼中的註解

2.ListIterator

ListIterator在Iterator基礎上提供了add、setprevious等對列表的操作。但是ListIterator跟Iterator一樣,仍是在原始列表上進行操作。

ListIterator原始碼如下:

/**
 * An iterator for lists that allows the programmer
 * to traverse the list in either direction, modify
 * the list during iteration, and obtain the iterator&#39;s
 * current position in the list. A {@code ListIterator}
 * has no current element; its <I>cursor position</I> always
 * lies between the element that would be returned by a call
 * to {@code previous()} and the element that would be
 * returned by a call to {@code next()}.
 * An iterator for a list of length {@code n} has {@code n+1} possible
 * cursor positions, as illustrated by the carets ({@code ^}) below:
 * <PRE>
 *           Element(0)  Element(1)  Element(2)  ... Element(n-1)
 * cursor positions: ^      ^      ^      ^         ^
 * 
 * Note that the {@link #remove} and {@link #set(Object)} methods are  * not defined in terms of the cursor position; they are defined to  * operate on the last element returned by a call to {@link #next} or  * {@link #previous()}.  *  * This interface is a member of the Java Collections Framework.*/ public interface ListIterator extends Iterator {   // Query Operations   /**    * Returns {@code true} if this list iterator has more elements when    * traversing the list in the forward direction. (In other words,    * returns {@code true} if {@link #next} would return an element rather    * than throwing an exception.)    *    * @return {@code true} if the list iterator has more elements when    *     traversing the list in the forward direction    */   boolean hasNext();   /**    * Returns the next element in the list and advances the cursor position.    * This method may be called repeatedly to iterate through the list,    * or intermixed with calls to {@link #previous} to go back and forth.    * (Note that alternating calls to {@code next} and {@code previous}    * will return the same element repeatedly.)    *    * @return the next element in the list    * @throws NoSuchElementException if the iteration has no next element    */   E next();   /**    * Returns {@code true} if this list iterator has more elements when    * traversing the list in the reverse direction. (In other words,    * returns {@code true} if {@link #previous} would return an element    * rather than throwing an exception.)    *    * @return {@code true} if the list iterator has more elements when    *     traversing the list in the reverse direction    */   boolean hasPrevious();   /**    * Returns the previous element in the list and moves the cursor    * position backwards. This method may be called repeatedly to    * iterate through the list backwards, or intermixed with calls to    * {@link #next} to go back and forth. (Note that alternating calls    * to {@code next} and {@code previous} will return the same    * element repeatedly.)    *    * @return the previous element in the list    * @throws NoSuchElementException if the iteration has no previous    *     element    */   E previous();   /**    * Returns the index of the element that would be returned by a    * subsequent call to {@link #next}. (Returns list size if the list    * iterator is at the end of the list.)    *    * @return the index of the element that would be returned by a    *     subsequent call to {@code next}, or list size if the list    *     iterator is at the end of the list    */   int nextIndex();   /**    * Returns the index of the element that would be returned by a    * subsequent call to {@link #previous}. (Returns -1 if the list    * iterator is at the beginning of the list.)    *    * @return the index of the element that would be returned by a    *     subsequent call to {@code previous}, or -1 if the list    *     iterator is at the beginning of the list    */   int previousIndex();   // Modification Operations   /**    * Removes from the list the last element that was returned by {@link    * #next} or {@link #previous} (optional operation). This call can    * only be made once per call to {@code next} or {@code previous}.    * It can be made only if {@link #add} has not been    * called after the last call to {@code next} or {@code previous}.    *    * @throws UnsupportedOperationException if the {@code remove}    *     operation is not supported by this list iterator    * @throws IllegalStateException if neither {@code next} nor    *     {@code previous} have been called, or {@code remove} or    *     {@code add} have been called after the last call to    *     {@code next} or {@code previous}    */   void remove();   /**    * Replaces the last element returned by {@link #next} or    * {@link #previous} with the specified element (optional operation).    * This call can be made only if neither {@link #remove} nor {@link    * #add} have been called after the last call to {@code next} or    * {@code previous}.    *    * @param e the element with which to replace the last element returned by    *     {@code next} or {@code previous}    * @throws UnsupportedOperationException if the {@code set} operation    *     is not supported by this list iterator    * @throws ClassCastException if the class of the specified element    *     prevents it from being added to this list    * @throws IllegalArgumentException if some aspect of the specified    *     element prevents it from being added to this list    * @throws IllegalStateException if neither {@code next} nor    *     {@code previous} have been called, or {@code remove} or    *     {@code add} have been called after the last call to    *     {@code next} or {@code previous}    */   void set(E e);   /**    * Inserts the specified element into the list (optional operation).    * The element is inserted immediately before the element that    * would be returned by {@link #next}, if any, and after the element    * that would be returned by {@link #previous}, if any. (If the    * list contains no elements, the new element becomes the sole element    * on the list.) The new element is inserted before the implicit    * cursor: a subsequent call to {@code next} would be unaffected, and a    * subsequent call to {@code previous} would return the new element.    * (This call increases by one the value that would be returned by a    * call to {@code nextIndex} or {@code previousIndex}.)    *    * @param e the element to insert    * @throws UnsupportedOperationException if the {@code add} method is    *     not supported by this list iterator    * @throws ClassCastException if the class of the specified element    *     prevents it from being added to this list    * @throws IllegalArgumentException if some aspect of this element    *     prevents it from being added to this list    */   void add(E e); }

ListIterator的功能更強大,定義的方法有:

  1).hasNext() 向前遍歷時,如果有下一個元素傳回真;

  2).next() 傳回下一個元素的值,並將指標加1;

  3).hasPrevious() 往相反方向遍歷時,如果還有元素傳回真;

  4).previous() 傳回上一個元素的值,並將指標前移1;

  5).nextIndex() 傳回此時呼叫next()方法時傳回的元素的索引;

  6).previousIndex() 傳回此時呼叫previous()方法時傳回的元素的索引;

  7).remove() 移除最近一次調用next()或previous()方法返回的元素(可選);

  8).set(E e) 用元素e將如果此時調用next()或previous()方法傳回的元素被替換掉;

  9).add(E e) 新增元素到此時呼叫next()傳回的元素之前,或此時呼叫previous()返回的元素之後。

更詳細的說明請閱讀原始碼中的註解。

3.Iterator與ListIterator的差異

#  Iterator與ListIterator的方法比較如下表:

##  nextIndex()  previousIndex()  set(E e)  add(E e)  

#Iterator

ListIterator

hasNext()

hasNext() 覆寫

#next()

next() 覆寫

remove()

#remove() 已覆寫

forEachRemaining(Consumer super E> action)

forEachRemaining(Consumer super E> action) 繼承
  hasPrevious()  
previous()

二者的差異主要有:

  1).Iterator只能單向移動,ListIterator可以雙向移動;

  2).ListIterator可以

刪除、替換或添加元素,而Iterator只能刪除元素;

#  3).ListIterator可以返回目前(呼叫next()或previous()傳回的)元素的索引,而Iterator不能。

以上是java中關於Iterator介面和LIstIterator介面的具體介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JVM如何在不同平台上管理垃圾收集?JVM如何在不同平台上管理垃圾收集?Apr 28, 2025 am 12:23 AM

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

為什麼Java代碼可以在不同的操作系統上運行,而無需修改?為什麼Java代碼可以在不同的操作系統上運行,而無需修改?Apr 28, 2025 am 12:14 AM

Java代碼可以在不同操作系統上無需修改即可運行,這是因為Java的“一次編寫,到處運行”哲學,由Java虛擬機(JVM)實現。 JVM作為編譯後的Java字節碼與操作系統之間的中介,將字節碼翻譯成特定機器指令,確保程序在任何安裝了JVM的平台上都能獨立運行。

描述編譯和執行Java程序的過程,突出平台獨立性。描述編譯和執行Java程序的過程,突出平台獨立性。Apr 28, 2025 am 12:08 AM

Java程序的編譯和執行通過字節碼和JVM實現平台獨立性。 1)編寫Java源碼並編譯成字節碼。 2)使用JVM在任何平台上執行字節碼,確保代碼的跨平台運行。

基礎硬件架構如何影響Java的性能?基礎硬件架構如何影響Java的性能?Apr 28, 2025 am 12:05 AM

Java性能与硬件架构密切相关,理解这种关系可以显著提升编程能力。1)JVM通过JIT编译将Java字节码转换为机器指令,受CPU架构影响。2)内存管理和垃圾回收受RAM和内存总线速度影响。3)缓存和分支预测优化Java代码执行。4)多线程和并行处理在多核系统上提升性能。

解釋為什麼本地庫可以破壞Java的平台獨立性。解釋為什麼本地庫可以破壞Java的平台獨立性。Apr 28, 2025 am 12:02 AM

使用原生庫會破壞Java的平台獨立性,因為這些庫需要為每個操作系統單獨編譯。 1)原生庫通過JNI與Java交互,提供Java無法直接實現的功能。 2)使用原生庫增加了項目複雜性,需要為不同平台管理庫文件。 3)雖然原生庫能提高性能,但應謹慎使用並進行跨平台測試。

JVM如何處理操作系統API的差異?JVM如何處理操作系統API的差異?Apr 27, 2025 am 12:18 AM

JVM通過JavaNativeInterface(JNI)和Java標準庫處理操作系統API差異:1.JNI允許Java代碼調用本地代碼,直接與操作系統API交互。 2.Java標準庫提供統一API,內部映射到不同操作系統API,確保代碼跨平台運行。

Java 9影響平台獨立性中引入的模塊化如何?Java 9影響平台獨立性中引入的模塊化如何?Apr 27, 2025 am 12:15 AM

modularitydoesnotdirectlyaffectJava'splatformindependence.Java'splatformindependenceismaintainedbytheJVM,butmodularityinfluencesapplicationstructureandmanagement,indirectlyimpactingplatformindependence.1)Deploymentanddistributionbecomemoreefficientwi

什麼是字節碼,它與Java的平台獨立性有何關係?什麼是字節碼,它與Java的平台獨立性有何關係?Apr 27, 2025 am 12:06 AM

BytecodeinJavaistheintermediaterepresentationthatenablesplatformindependence.1)Javacodeiscompiledintobytecodestoredin.classfiles.2)TheJVMinterpretsorcompilesthisbytecodeintomachinecodeatruntime,allowingthesamebytecodetorunonanydevicewithaJVM,thusfulf

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。