Maison > Java > javaDidacticiel > le corps du texte

Une introduction détaillée à l'interface Iterator et à l'interface LIstIterator en Java

黄舟
Libérer: 2017-05-28 09:08:19
original
1495 Les gens l'ont consulté

Cet article présente principalement les informations pertinentes sur l'analyse de l'interface java Iterator et LIstIterator. Les amis qui en ont besoin peuvent se référer à

Interface Java Iterator et analyse de l'interface LIstIterator

Répertoire

1.Interface Iterator

2.ListIterator
3.Iterator et La différence entre ListIterator

Text

Avant de continuer à examiner le code source de

ArrayList, comprenez d'abord l'interface Iterator et l'interface ListIterator. Le prochain article expliquera ArrayList en détail Comment les implémenter.

Nous savons qu'une interface n'est qu'une spécification. Lorsque

hérite de l'interface et implémente ses méthodes, la description des méthodes par l'interface doit être suivie.

1. Interface Iterator

L'interface Iterator remplace l'Enumeratrion dans le framework Java collection

. Les itérateurs diffèrent des énumérations sur deux points principaux :

Les itérateurs permettent à l'appelant de supprimer des éléments de la collection pendant le processus d'itération ;

Le nom de la méthode a été amélioré.

Le code source de l'Iterator est le suivant :

/**
 * 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()); } }
Copier après la connexion
L'interface Iterator définit quatre méthodes et les fonctions de chaque méthode si une classe implémente cette interface et les implémente. Méthode, cette méthode doit implémenter la fonction définie et suivre ces règles :

 1).hasNext() détermine si le conteneur a l'élément suivant et renvoie true s'il y en a ; ).next( ) Renvoie l'élément suivant dans le conteneur ;

 3).remove() supprime le dernier élément renvoyé par l'itérateur actuel. Cette méthode ne peut être appelée qu'une seule fois après chaque appel à la méthode next() ;

 4). Java 8 ajoute la méthode forEa

chR

emaining, qui peut exécuter l'exécution spécifiée sur tous les autres. éléments.

Pour des instructions plus détaillées, veuillez lire les commentaires

dans le code source.

2. ListIterator

ListIterator fournit un ajout, un
set

, un

précédentious, etc. Opérations sur les listes. Mais ListIterator, comme Iterator, fonctionne toujours sur la liste d'origine. Le code source de ListIterator est le suivant :

ListIterator est plus puissant et les méthodes définies sont :

/**
 * 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); }
Copier après la connexion
 1).hasNext( ) forward Lors du parcours, s'il y a un élément suivant, return true

 2).next() renvoie la valeur de l'élément suivant et ajoute 1 au pointeur ; hasPrevious() fait le contraire Lors du déplacement dans la direction, s'il y a encore des éléments, return true

 4).previous() renvoie la valeur de l'élément précédent et avance le pointeur de 1 ; >

 5).nextIndex() renvoie l'index

de l'élément renvoyé lorsque la méthode next() est appelée à ce moment

 6).previousIndex() renvoie l'index ; de l'élément renvoyé lorsque la méthode previous() est appelée à ce moment ;

 7).remove() supprime l'élément renvoyé par l'appel le plus récent à la méthode next() ou previous() (facultatif) ;

 8).set(E e) Utilisez l'élément e pour définir si ceci Remplacez l'élément renvoyé en appelant la méthode next() ou previous()

 9).add(E e) Ajoutez un élément avant l'élément renvoyé en appelant next() à ce moment-là, ou appelez previous() à ce moment-là) après l'élément renvoyé.

Pour des instructions plus détaillées, veuillez lire les commentaires dans le code source.

3. La différence entre Iterator et ListIterator

Les méthodes de Iterator et ListIterator sont comparées dans le tableau suivant :

remove()

Itérateur

ListIterator
hasNext()

hasNext() Remplacer
suivant( )

Iterator

ListIterator

 

hasNext()

hasNext() 覆盖

next()

next() 覆盖

remove()

remove() 覆盖

forEachRemaining(Consumer action)

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

supprimer()

Remplacer
forEachRemaining (Consumer action) td> forEachRemaining (Consumer action) Hérité
hasPrevious()
précédent()
nextIndex()
previousIndex()
set(E e)
add(E e )

Les principales différences entre les deux sont :

 1) .Iterator ne peut se déplacer que dans une seule direction, tandis que ListIterator peut se déplacer dans deux directions

 2).ListIterator peut

supprimer , remplacer ou ajouter des éléments, tandis qu'Iterator ne peut que supprimer ; elements; 3).ListIterator peut renvoyer l'index de l'élément actuel (renvoyé en appelant next() ou previous()), mais Iterator ne le peut pas.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!