I know there is no direct equivalent in Java itself, but perhaps a third party?
It is really convenient. Currently I'd like to implement an iterator that yields all nodes in a tree, which is about five lines of code with yield.
Java and C# are incredibly similar. Both languages are somewhat derived from C++ and from similar first principles. Java was developed in 1995 to create a language with a simpler programming model than C++ while still preserving some of the same syntax of the language to facilitate developers transitioning to it.
Java doesn't have pointers; Java has references.
The char keyword is a data type that is used to store a single character. A char value must be surrounded by single quotes, like 'A' or 'c'.
Lower-bound is when you specify (? super Field) means argument can be any Field or superclass of Field. Try following code: Uncomment the code and check if any error comes. import java.util.ArrayList; import java.util.Collection; public class GenericsDemo { public static void validateTillStringType(Collection<?
The two options I know of is Aviad Ben Dov's infomancers-collections library from 2007 and Jim Blackler's YieldAdapter library from 2008 (which is also mentioned in the other answer).
Both will allow you to write code with yield return
-like construct in Java, so both will satisfy your request. The notable differences between the two are:
Aviad's library is using bytecode manipulation while Jim's uses multithreading. Depending on your needs, each may have its own advantages and disadvantages. It's likely Aviad's solution is faster, while Jim's is more portable (for example, I don't think Aviad's library will work on Android).
Aviad's library has a cleaner interface - here's an example:
Iterable<Integer> it = new Yielder<Integer>() { @Override protected void yieldNextCore() { for (int i = 0; i < 10; i++) { yieldReturn(i); if (i == 5) yieldBreak(); } } };
While Jim's is way more complicated, requiring you to adept
a generic Collector
which has a collect(ResultHandler)
method... ugh. However, you could use something like this wrapper around Jim's code by Zoom Information which greatly simplifies that:
Iterable<Integer> it = new Generator<Integer>() { @Override protected void run() { for (int i = 0; i < 10; i++) { yield(i); if (i == 5) return; } } };
Aviad's solution is BSD.
Jim's solution is public domain, and so is its wrapper mentioned above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With