日期:2014-05-20  浏览次数:20788 次

关于iterator的remove方法的问题
本帖最后由 raylee2007 于 2013-01-09 16:22:00 编辑

package com.nbgnuskin.collection;

import java.util.*;

public class IteratorTest {

public IteratorTest() {
// TODO Auto-generated constructor stub
}

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
Collection c = new HashSet();
c.add(new Name("a1","b1"));
c.add(new Name("a2222","b2"));
c.add(new Name("a3","b3"));
c.add(new Name("a4","b4"));
// while(i.hasNext())
// {
// Name n = (Name) i.next();
// if(n.getfirstName().length() > 3)
// {
// i.remove();
// }
// System.out.println(n.getfirstName() + " " + n.getfirstName().length());
// }
for(Iterator i = c.iterator();i.hasNext();)
{
Name n = (Name)i.next();
if (n.getfirstName().length() > 3) {
i.remove(); }
System.out.println(n.getfirstName() + " " + n.getfirstName().length());
}
}

}


上面写了一个小程序,主要是测试iterator的remove方法,为什么中间的那个remove方法没有作用?谢谢

------解决方案--------------------

public static void main(String[] args) {

 Collection c = new HashSet();
        c.add(new Name("a1","b1"));
        c.add(new Name("a2222","b2"));
        c.add(new Name("a3","b3"));
        c.add(new Name("a4","b4"));
//         while(i.hasNext())
//         {
//             Name n = (Name) i.next();
//             if(n.getfirstName().length() > 3)
//             {
//                 i.remove();
//             }
//             System.out.println(n.getfirstName() + " " + n.getfirstName().length());
//         }
      
        for(Iterator i = c.iterator();i.hasNext();)
        {
         System.out.println(i.toString());
            Name n = (Name)i.next();
            if (n.getFirstName().length() > 3) {
                c.remove(i);        //这一句,看区别    }
            System.out.println(n.getFirstName() + " " + n.getFirstName().length());