ホームページ  >  記事  >  Java  >  Java の Iterator インターフェイスと LIstIterator インターフェイスの詳細な紹介

Java の Iterator インターフェイスと LIstIterator インターフェイスの詳細な紹介

黄舟
黄舟オリジナル
2017-05-28 09:08:191496ブラウズ

この記事では主に Java IteratorインターフェースLIstIteratorインターフェース解析の関連情報を紹介しますので、必要な方は

Java IteratorインターフェースとLIstIteratorインターフェース解析

目次

を参照してください。

1 .Iterator インターフェース
2. ListIterator
3. Iterator と ListIterator の違い

テキスト

ArrayList のソースコードを見続ける前に、まず Iterator インターフェースと ListIterator インターフェースについて理解します。 ArrayList がそれらをどのように実装するかを詳しく説明します。

インターフェースが単なる仕様であることはわかっています。 がインターフェースを継承してそのメソッドを実装する場合、インターフェースのメソッドの説明に従わなければなりません。

1.Iterator インターフェイス

Iterator インターフェイスは、Java コレクション

フレームワーク の Enumeratrion を置き換えます。イテレータは主に 2 つの点で列挙型と異なります。

イテレータを使用すると、呼び出し元は反復プロセス中にコレクションから要素を削除できます。

メソッド名が改良されました。

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 action) { Objects.requireNonNull(action); while (hasNext()) action.accept(next()); } }

Iterator インターフェイスは 4 つのメソッドと各メソッドの関数を定義します。クラスがこのインターフェイスを実装し、これらのメソッドを実装する場合、このメソッドは定義された関数を実装し、次の規則に従う必要があります。

1).hasNext() はコンテナに次の要素があるかどうかを判断し、ある場合は true を返します。

2).next() はコンテナ内の次の要素を返します。 iterator 返される最後の要素。このメソッドは、next() メソッドを呼び出すたびに 1 回だけ呼び出すことができます。4) Java 8 では、残りのすべての要素に対して指定された操作を実行できる forEa

chR

emaining メソッドが追加されています。

さらに詳しい手順については、ソースコードの

コメントをご覧ください。

2. ListIterator

ListIterator は、Iterator に基づいた add、set
prev

ious およびその他のリスト操作を提供します。ただし、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() 前方にトラバースする場合、次の要素がある場合は true を返します。 2).next( ) 次の要素の値を返し、ポインタに 1 を加算します。

3).hasPrevious() 逆方向にトラバースする場合、まだ要素がある場合は true を返します。 previous() は前の要素の値を返し、ポインタを 1 つ進めます

5).nextIndex() は、この時点で next() メソッドが呼び出されたときに返される要素の

index を返します。 ).previousIndex() は、previous() メソッドがこの時点で呼び出されたときに返されるものを返します 要素のインデックス

7).remove() は、最新の next() またはprevious() の呼び出しによって返された要素を削除します。 ) メソッド (オプション);

8).set(E e) 要素 e を使用して if this を呼び出して返された要素を置き換えます

9).add(E e) を追加します。この時点で next() を呼び出して返された要素の前の要素、またはこの時点で next() を呼び出して返された要素の後の要素。

さらに詳しい手順については、ソースコード内のコメントを読んでください。

3. Iterator と ListIterator の違い

次の表で Iterator と ListIterator のメソッドを比較します。

は次( )

次があります ()
オーバーレイ

next()オーバーレイremove() forEachRemaining(Consumer0d74ac1b2f8f9ab0eb66f930789a9645action)hasPrevious()前() nextIndex()previousIndex()set(E e)add(E e) 2 つの違い 主な機能は次のとおりです: 3) .ListIterator は現在の要素のインデックス (next() またはprevious() の呼び出しによって返される) を返すことができますが、Iterator はできません。

next()

remove()

オーバーレイ

forEachRemaining (Consumer0d74ac1b2f8f9ab0eb66f930789a9645 action)

inherit

1) Iterator は 1 つの方向にのみ移動できますが、ListIterator は 2 つの方向に移動できます。 Iterator は要素の削除のみ可能です;

以上がJava の Iterator インターフェイスと LIstIterator インターフェイスの詳細な紹介の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。