Heim > Java > javaLernprogramm > Hauptteil

Eine detaillierte Einführung in die Iterator-Schnittstelle und die LIstIterator-Schnittstelle in Java

黄舟
Freigeben: 2017-05-28 09:08:19
Original
1495 Leute haben es durchsucht

In diesem Artikel werden hauptsächlich die relevanten Informationen zur Java-Iterator-Schnittstelle und zur LIstIterator-Schnittstellenanalyse vorgestellt >Java-Iterator-Schnittstelle und LIstIterator-Schnittstellenanalyse

Verzeichnis

1.Iterator-Schnittstelle2.ListIterator

3.Iterator und Der Unterschied zwischen ListIterator



Text

Bevor Sie sich den Array

List-Quellcode ansehen, sollten Sie zunächst die Iterator-Schnittstelle und die ListIterator-Schnittstelle verstehen. Im nächsten Artikel wird ArrayList ausführlich erläutert, wie man sie implementiert.

Wir wissen, dass eine Schnittstelle nur eine Spezifikation ist. Wenn die Schnittstelle

erbt und ihre Methoden implementiert, muss die Beschreibung der Methoden der Schnittstelle befolgt werden.

1. Iterator-Schnittstelle

Die Iterator-Schnittstelle ersetzt das Enumeratrion im Java-Collection-
-Framework

. Iteratoren unterscheiden sich von Aufzählungen in zwei Hauptpunkten:

Iteratoren ermöglichen es dem Aufrufer, während des Iterationsprozesses Elemente aus der Sammlung zu entfernen

Der Methodenname wurde verbessert.

Der Iterator-Quellcode lautet wie folgt:

Die Iterator-Schnittstelle definiert vier Methoden und die Funktionen jeder Methode. Wenn eine Klasse diese Schnittstelle implementiert, implementiert sie diese Methode, diese Methode muss die definierte Funktion implementieren und diese Regeln befolgen:

/**
 * 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()); } }
Nach dem Login kopieren
1).hasNext() bestimmt, ob der Container das nächste Element hat, und gibt true zurück, wenn es vorhanden ist;

2 ).next( ) Gibt das nächste Element im Container zurück

 3).remove() entfernt das letzte vom aktuellen Iterator zurückgegebene Element. Diese Methode kann nur einmal nach jedem Aufruf der next()-Methode aufgerufen werden;

 4). Elemente.

Für detailliertere Anweisungen lesen Sie bitte die

Kommentare im Quellcode.

2. ListIterator

ListIterator bietet add, set,
prev

ious usw. basierend auf Iterator . Operationen auf Listen. Aber ListIterator arbeitet wie Iterator immer noch mit der ursprünglichen Liste.

Der Quellcode von ListIterator lautet wie folgt:

ListIterator ist leistungsfähiger und die definierten Methoden sind:  1).hasNext( ) vorwärts Wenn es ein nächstes Element gibt, gib true zurück

/**
 * 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); }
Nach dem Login kopieren
 2).next() gibt den Wert des nächsten Elements zurück und fügt 1 zum Zeiger hinzu; hasPrevious() macht das Gegenteil. Wenn beim Durchlaufen in die Richtung noch Elemente vorhanden sind, geben Sie true zurück

 4). previous() gibt den Wert des vorherigen Elements zurück und bewegt den Zeiger um 1 vorwärts; >

 5).nextIndex() gibt den

-Index des Elements zurück, das zu diesem Zeitpunkt zurückgegeben wird, wenn die next()-Methode aufgerufen wird.

 6). previousIndex() gibt den Index zurück des Elements, das zu diesem Zeitpunkt zurückgegeben wird, wenn die Methode previous() aufgerufen wird;

 7).remove() entfernt das Element, das vom letzten Aufruf der Methode next() oder previous() zurückgegeben wurde (optional);

 8).set(E e) Verwenden Sie Element e, um festzulegen, ob dies das zurückgegebene Element ersetzt, indem Sie die Methode next() oder previous() aufrufen  9).add(E e) Fügen Sie ein Element vor dem zurückgegebenen Element hinzu, indem Sie zu diesem Zeitpunkt next() aufrufen, oder rufen Sie zu diesem Zeitpunkt previous() auf, nachdem das Element zurückgegeben wurde.

Für detailliertere Anweisungen lesen Sie bitte die Kommentare im Quellcode.

3. Der Unterschied zwischen Iterator und ListIterator

Die Methoden von Iterator und ListIterator werden in der folgenden Tabelle verglichen:

remove()
Iterator

ListIterator

hasNext()
hasNext() Override

next( )

next() override

Iterator

ListIterator

 

hasNext()

hasNext() 覆盖

next()

next() 覆盖

remove()

remove() 覆盖

forEachRemaining(Consumer action)

forEachRemaining(Consumer action) 继承
  hasPrevious()  
  previous()  
  nextIndex()  
  previousIndex()  
  set(E e)  
  add(E e)  
remove()

Override
forEachRemaining(Consumer action) td> forEachRemaining(Consumer action) Inherited
hasPrevious()
previous()
nextIndex()
previousIndex()
set(E e)
add(E e )

Die Hauptunterschiede zwischen den beiden sind:

 1) .Iterator kann sich nur in eine Richtung bewegen, während ListIterator sich in zwei Richtungen bewegen kann

 2).ListIterator kann Elemente

löschen

, ersetzen oder hinzufügen, während Iterator nur löschen kann elements; 3).ListIterator kann den Index des aktuellen Elements zurückgeben (zurückgegeben durch Aufruf von next() oder previous()), Iterator jedoch nicht.

Das obige ist der detaillierte Inhalt vonEine detaillierte Einführung in die Iterator-Schnittstelle und die LIstIterator-Schnittstelle in Java. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!