简体   繁体   中英

Using a class within an enhanced for-loop

I've written a class that implements Collection and Iterable, and I am attempting to run it through an enhanced for-loop now. You can find it here: LinkedQueue

The point of the class is to be able to go through the collection using LinkedQueue.getNext(), which works fine. However I also want to be able to iterate over the values once using a for loop. The current code:

LinkedQueue<String> queue = new LinkedQueue();
queue.add("Test one");
queue.add("Test two");
queue.add("Test three");
System.out.println("queue.size = " + queue.size());
System.out.println("contents:");
for (String s : queue) {
    System.out.print("Test: ");
    System.out.println(s);
}
System.out.println("contents (x9):");
for (int i = 0; i < 9; i++) {
    System.out.println(queue.getNext());
}

Prints out this:

queue.size = 3
contents:
contents (x9):
Test one
Test two
Test three
...etc...

So it seems that the for loop isn't printing properly. I don't think it's an issue of size, since the queue has a size of 3 before starting. So now my problem is most likely "what is wrong with the iterable methods", which are hasNext() , next() , and remove() (which is unsupported in this queue). What am I doing wrong?

Your implementation is failing because when you (implicitly) call iterator() , your itr variable still refers to just the "null value" node. You only set it to any other value in the next() method, which isn't called until later.

However, there's a more serious design problem. Fundamentally, a collection should pretty much never implement iterator() itself. You should normally be able to iterate over an collection multiple times - potentially with multiple iterators at the same time, which should all be independent. Iterating over the collection shouldn't change it.

It's not entirely clear what you're trying to achieve, but an iterator() implementation should nearly always create a new object with some mutable state, which refers to the original collection but doesn't alter it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM