用循环子删除一个列表元素时的错误

rollrock 2004-04-30 08:44:49
ArrayListDemo这个类用循环子删除一个列表元素时,报错:
arraylistdemo.java:19: remove() in java.util.Iterator cannot be applied to (int)

useriter.remove(2);
^
1 error
源代码:
package com.wrox.utilities;
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListDemo{
public static void main(String[] args){
user usr1=new user("J Smith","123-444-4444");
user usr2=new user("M Walker","123-555-5555");
user usr3=new user("R Johnson","123-666-6666");
ArrayList userlist=new ArrayList();
userlist.add(usr3);
userlist.add(usr1);
userlist.add(usr2);
user usr=(user)userlist.get(1);
System.out.println("second user...");
System.out.println("username:"+usr.getUsername());
System.out.println("user phone number:"+usr.getPhoneNumber());
System.out.println("userlist...");
Iterator useriter=userlist.iterator();
useriter.remove(2);//此行
while (useriter.hasNext())
{
usr=(user)useriter.next();
System.out.println("username:"+usr.getUsername());
System.out.println("user phone number:"+usr.getPhoneNumber());
}
}
}
...全文
96 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
rollrock 2004-05-02
  • 打赏
  • 举报
回复
to yangzuyu12:
这种问题怎么了?这种问题怎么不能问,经常见到这么“牛”的人,别忘了,你也曾经是初学者,你也曾经因为一个简单的问题调试不出来,苦苦思索,难道这个时候不该问问吗?
danceflash 2004-04-30
  • 打赏
  • 举报
回复
ArrayList支持remove(int)
迭代子不支持

请楼主看清API

remove
public void remove()
Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be called only once per call to 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.

Throws:
UnsupportedOperationException - if the remove operation is not supported by this Iterator.
IllegalStateException - if the next method has not yet been called, or the remove method has already been called after the last call to the next method.

另外,迭代子与ResultSet一样,对象的初始状态不没有指向任何一条记录,要先执行next()
rollrock 2004-04-30
  • 打赏
  • 举报
回复
up
rollrock 2004-04-30
  • 打赏
  • 举报
回复
书上怎么说可以按索引删除呢,况且,不写索引,删除好像也报错
casemy 2004-04-30
  • 打赏
  • 举报
回复
方法用错了
remove方法不接受参数
yangzuyu12 2004-04-30
  • 打赏
  • 举报
回复
疯了,这种问题也拿出来问

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧