首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

关于测试迭代器Iterator使用的报错情况,请帮忙看看

2012-12-23 
关于测试迭代器Iterator使用的报错情况,请大虾帮忙看看import java.util.*public class TestCollection{p

关于测试迭代器Iterator使用的报错情况,请大虾帮忙看看

import java.util.*;
public class TestCollection
{
public static void main(String[] args)
{
Collection c = new HashSet();
c.add(new Name("Yun", "Ma"));
c.add(new Name("Pengxiang", "Mei"));
c.add(new Name("Bill", "Gates"));
for (Iterator i = c.iterator();i.hasNext();)
{
Name n = (Name)i.next();
while(n.getFirstName() == "Bill")
{
i.remove();
}
}
System.out.println(c);
}
}

class Name
{
private String firstName,lastName;
public Name(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName(){return firstName;}
public String getLastName(){return lastName;}
public String toString() {return firstName + " " + lastName;}

public boolean equals(Object obj)
{
if (obj instanceof Name)
{
Name name = (Name)obj;
return (this.firstName.equals(name.firstName))
&& (this.lastName.equals(name.lastName));
}
else 
{
return super.equals(obj);
}
}

public int hashCode()
{
return firstName.hashCode();
}
}

报错的信息是:Exception in thread "main" java.lang.IllegalStateException
        at java.util.HashMap$HashIterator.remove(HashMap.java:910)
        at TestCollection.main(TestCollection.java:15)
有点百撕不得骑姐的感觉。这个异常代表什么意思呢?
[解决办法]
在while的循环中好像要加上
n = (Name)i.next();
防止死循环的

热点排行