0

My objective is to iterate over a list of objects, and have the two functionalities: - be able to remove from the list during iteration. - be able to access the public get methods of the objects I'm iterating over, to be able to determine whether or not they should be removed.

For example, how would I get the following to work? Currently it gives the exception 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 Answers 4

3

it is a ListIterator<TestClass> instance, hence it doesn't have the getFoo() method.

You should use next() to fetch the next element and then remove it if needed:

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

  if (current.getFoo() == 2)
    it.remove();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Does this work if I want to change the internal state of the object inside the list while in the loop (through setter methods)?
1

Need change

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

to

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

1 Comment

you can't call getFoo() on an Iterator
0

You have a problem in your code here:

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

it is an Iterator<TestClass> not a TestClass, therefore you are getting an error that $Itr cannot be cast to random.folder.dir.TestClass. What you are doing is similar to casting an ArrayList<String> to a String, you have a bunch of TestClass objects, not just one.

Use an iterator like this:

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

Comments

0

The next () funcion returns the object 'pointed to' by the iterator. Use it as you wish.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.