kes*_*ari 0 java iterator arraylist
我正在尝试使用"Iterator".remove删除此ArrayList中具有偶数索引号的字符串.
import java.util.*;
import static java.lang.System.out;
class MAIN
{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
Iterator i = al.iterator();
int len;
Scanner sc = new Scanner(System.in);
out.printf("Size:");
len = sc.nextInt();
while( len!=0 )
{
al.add( sc.next() );
len -= 1;
}
Object o;
for( len = 0 ; len < al.size() ; len +=1)
{
out.println(al);
if( len%2==0 )
{
o = i.next();
out.println(o);
i.remove();
i.next();
}
}
return;
}
}
Run Code Online (Sandbox Code Playgroud)
我在i.next();得到了"ConcurrentModificationException".怎么了 ?
您没有使用迭代器来迭代校正,因此您无法使用它来删除元素.要正确使用它,必须使用迭代器本身循环.
即
for (Iterator<E> iter = list.iterator(); iter.hasNext(); ) {
E element = iter.next();
// 1 - can call methods of element
// 2 - can use iter.remove() to remove the current element from the list
// ...
}
Run Code Online (Sandbox Code Playgroud)
也许是这样的:
int count = 0;
for (Iterator<String> iter = al.iterator(); iter.hasNext(); ) {
String element = iter.next();
System.out.print(element);
if (count % 2 == 0) {
iter.remove();
System.out.print(" -- has been deleted");
}
System.out.println();
count++;
}
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用for循环向后循环遍历您的集合.这可以工作,因为删除项目不会更改项目在删除项目之前的排序或索引.
| 归档时间: |
|
| 查看次数: |
99 次 |
| 最近记录: |