I\'ve created a linked list in java using generics, and now I want to be able to iterate over all the elements in the list. In C# I would use yield return
insid
try this
check this article for a sample implementation as well:
If you want the full functionality of yield return
, you probably need to set this up in two threads-- one for the first method, and one for the second. Then the first thread should wait
until the second thread puts its value somewhere accessible and notify
s it that it's ready. Then the first thread would process that value, wait
for the next value, etc.
I don't understand why people are talking about threads... is there something I don't know about yield return?
To my understanding yield return just saves the method stack and restores it at a later time. To implement yield return you just have to save the state manually. See the Java iterator classes for details, though for a linked list you can just get away with saving the current item. For an array you'd just need the index.
use my java library to realize yield return without using threads or byte code manipulation
http://www.heinerkuecker.de/YieldReturnForNested.html
It's been ages since this question was posted, and I'm quite unsure about writing an answer to such an old question, but another way of achieving this has occurred to me and I want to present it here in case it helps anyone searching for this, given the fact that this SO thread was one of the very first hits in Google.
The code shown below has been compiled in my head. There's absolutely no guarantee it's correct, but the idea behind it is.
Use callbacks
Yes, I know, it is not the same as a yield return
. But I don't think OP wanted specifically a replacement that could be (with the appropriate amount of sugar) dropped into a for (var x : <some_iterator>)
. My approach instead does something more akin to C#'s linq
(or Java's stream()
), not the yield
ed return.
@FunctionalInterface
public interface Looper<T> {
void each(T item);
}
public interface Loopable<T> {
void forEach(Looper<? super T> looper);
}
Then you would implement Loopable<T>
in your code, creating this pseudo-iterator. Which is really not, it's just making use of @FunctionalInterface
s, which is Java's way of doing callbacks (sorta)
public class WhatEvs implements Loopable<WhatEvs> {
// ...
@Override
public void forEach(Looper<? super T> looper) {
while(your_condition) {
WhatEvs nextItem = getNextItem();
looper.each(nextItem);
}
}
}
Am I missing something here? There is already java.util.LinkedList, it is fully generics-enabled, and it has a method which returns an Iterator.
If you really want to re-invent the wheel, I'd suggest you look into to creating a LinkedListIterator class, probably implementing ListIterator. It would remember its current position within the linked list and advance it on each successive call.