在程序开发中可能遇到下面的问题,如果一个list,需要在循环的时候,动态的添加一个元素进去那该怎么办呢?
 
如果直接在循环中add,势必会抛出异常。那要怎么添加呢?下面就是现在要说的ListIterator,利用ListIterator
动态的给list添加元素。
 
我们先看看文档:
地址:
http://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html
内容: 
public interface ListIterator<E> extends Iterator<E>
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 ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). An iterator for a list of length n has n+1 possible cursor positions, as illustrated by the carets (^) below:
 
 Element(0)   Element(1)   Element(2)   … Element(n-1)
 

Note that the remove() and 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 next() or previous().This interface is a member of the Java Collections Framework.

 

列表的迭代器允许程序员在任一方向上遍历列表,在迭代期间修改列表元素,并获得列表中的迭代器的当前位置。

add方法异常:
Throws:

UnsupportedOperationException – if the add method is not supported by this list iterator

ClassCastException – if the class of the specified element prevents it from being added to this list

IllegalArgumentException – if some aspect of this element prevents it from being added to this list

写个小示例:

 

输出:
[1, 3, 2]
over
分类: java

guolin

guolin

相信世界,向往美好,记录成长过程,分享个人心得,充实平凡生活。 网站信条:因为喜欢,所以热爱。

发表评论

电子邮件地址不会被公开。 必填项已用*标注