这篇文章主要介绍了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>{@code
* while (hasnext())
* action.accept(next());
* }</pre>
*
* @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、set、previous等对列表的操作。但是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'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: ^ ^ ^ ^ ^
* </pre>
* note that the {@link #remove} and {@link #set(object)} methods are
* <i>not</i> 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<e> extends iterator<e> {
// 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的方法对比如下表:
iterator
listiterator
hasnext()
hasnext() 覆盖
next()
next() 覆盖
remove()
remove() 覆盖
foreachremaining(consumer0d74ac1b2f8f9ab0eb66f930789a9645 action)
foreachremaining(consumer0d74ac1b2f8f9ab0eb66f930789a9645 action) 继承
hasprevious()
previous()
nextindex()
previousindex()
set(e e)
add(e e)
二者的不同之处主要有:
1).iterator只能单向移动,listiterator可以双向移动;
2).listiterator可以删除、替换或添加元素,而iterator只能删除元素;
3).listiterator可以返回当前(调用next()或previous()返回的)元素的索引,而iterator不能。
以上就是java中关于iterator接口和listiterator接口的具体介绍的详细内容。