使用List Iterator时访问对象的方法

时间:2013-11-19 03:40:42

标签: java list arraylist iterator

我的目标是迭代一个对象列表,并具有两个功能: - 能够在迭代期间从列表中删除。 - 能够访问我正在迭代的对象的公共get方法,以便能够确定是否应该删除它们。

例如,我如何才能使以下工作?目前它提供例外java.util.ArrayList$Itr cannot be cast to random.folder.dir.TestClass

public class TestClass {
    public int foo;

    public TestClass(int foo) {
        this.foo = foo;
    }

    public int getFoo() {
        return foo;
    }       
}




List<TestClass> testList = new ArrayList<TestClass>();
testList.add(new TestClass(1));
testList.add(new TestClass(2));
testList.add(new TestClass(3));

Iterator<TestClass> it = tickScratch.iterator();
while(it.hasNext()) {
    if(((TestClass)it).getFoo() == 2)
        it.remove();
}

4 个答案:

答案 0 :(得分:2)

itListIterator<TestClass>个实例,因此它没有getFoo()方法。

您应该使用next()来获取下一个元素,然后在需要时将其删除:

while (it.hasNext() {
  TestClass current = it.next(); 

  if (current.getFoo() == 2)
    it.remove();
}

答案 1 :(得分:1)

需要改变

  if(((TestClass)it).getFoo() == 2)

    if(it.getNext().getFoo() == 2)

答案 2 :(得分:0)

您的代码存在问题:

Iterator<TestClass> it = tickScratch.iterator();
while(it.hasNext()) {
    if(((TestClass)it).getFoo() == 2)
        it.remove();
}

itIterator<TestClass>而不是TestClass,因此您收到的错误为$Itr cannot be cast to random.folder.dir.TestClass。你正在做的事情类似于将ArrayList<String>投射到String,你有一堆TestClass个对象,而不只是一个。

使用这样的迭代器:

Iterator<TestClass> it = tickScratch.iterator();
while(it.hasNext()) {
    if(it.next().getFoo() == 2)
        it.remove();
}

答案 3 :(得分:0)

next ()函数返回迭代器'指向'的对象。根据需要使用它。

http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html#next()

相关问题