package TestIterator;import java.util.*;
public class TestIterator { public static void main(String[] args) {
Collection c = new HashSet();
c.add(new Name("f1", "L1"));
c.add(new Name("f3", "L3"));
c.add(new Name("f2", "L2"));
c.add(new Name("f4", "L4"));
c.add(new Name("f41111111111111", "L5"));
c.add("Hello");
Iterator i = c.iterator();

while (i.hasNext()) {
Name n = (Name) i.next();
if(n.getFirstName().length()>3){
i.remove();

} System.out.println(n.getFirstName() + " " + n.getLastName());
}  
}}class Name {
public String getFirstName() {
return FirstName;
} public String getLastName() {
return LastName;
} public Name(String FirstName, String LastName) {
this.FirstName = FirstName;
this.LastName = LastName;
} @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((FirstName == null) ? 0 : FirstName.hashCode());
result = prime * result
+ ((LastName == null) ? 0 : LastName.hashCode());
return result;
} @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Name other = (Name) obj;
if (FirstName == null) {
if (other.FirstName != null)
return false;
} else if (!FirstName.equals(other.FirstName))
return false;
if (LastName == null) {
if (other.LastName != null)
return false;
} else if (!LastName.equals(other.LastName))
return false;
return true;
} public String toString() {
return FirstName + " " + LastName; } private String FirstName, LastName;
}
运行结果为:
f3 L3
f2 L2
Exception in thread "main" java.lang.ClassCastException: java.lang.String
at TestIterator.TestIterator.main(TestIterator.java:32)我没用那个泛型。不过我觉得这样也可以吧,这个错误时为什么呢?谢谢回答!

解决方案 »

  1.   

    c.add("Hello");Name n = (Name) i.next();Hello没法转换成Name把c.add("Hello");去掉就OK了
      

  2.   

    加个类型判断也行
    while(i.hasNext()){
    Object o = i.next();
    if(o instanceof Name){
    Name n = (Name) o;
    if(n.getFirstName().length() > 3){
    i.remove();
    }
    System.out.println(n.getFirstName() + " " + n.getLastName());
    }
    }
      

  3.   

    都的,你放入的是name 和string类型,迭代的时候 你全认为 是 name类型
    当然 出错了 。呵呵 
      

  4.   

    但是我不能remove掉那个f41111111111111,是怎么回事?
      

  5.   

    for (Iterator i = c.iterator(); i.hasNext();) {
    Object o = i.next();
    if (o instanceof Name) {
    Name n = (Name) o; if (n.getFirstName().length() > 3) {
    i.remove(); }
    }
    }
    System.out.println(c);
    用这个的可以,这个for跟那个while有区别么?