Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent to IEnumerator from C#?

Are there interfaces in Java library, which also enumerates some series, but follows slightly another logic than Iterator and Enumeration? Namely they should return boolean on next(), saying whether next element was reached, and should have getCurrent() method, which returns current element?

UPDATE

Iterator.next() is not equivalent of IEnumerator.Current since former will advance iterator on each call while latter won't.

UPDATE 2

I am designing my own class with my own functionality. My question was in order to find a "competent" analogy. The sample from C# was just a sample, I am not translating something from C# to Java.

like image 957
Suzan Cioc Avatar asked Oct 24 '25 14:10

Suzan Cioc


2 Answers

This sounds like Guava's PeekingIterator; you can decorate a plain Iterator with Iterators.peekingIterator.

like image 109
Louis Wasserman Avatar answered Oct 26 '25 04:10

Louis Wasserman


You have to use a different approach in Java. e.g., instead of this C# code:

Dictionary<int?, int?> m = new Dictionary<int?, int?>();
for (IEnumerator<KeyValuePair<int?, int?>> it = m.GetEnumerator(); it.MoveNext();)
{
    Console.Write(it.Current.Key);
    Console.Write(it.Current.Value);
}

You will need to use:

java.util.HashMap<Integer, Integer> m = new java.util.HashMap<Integer, Integer>();
for (java.util.Iterator<java.util.Map.Entry<Integer, Integer>> it = m.entrySet().iterator(); it.hasNext();)
{
    java.util.Map.Entry<Integer, Integer> current = it.next();
    System.out.print(current.getKey());
    System.out.print(current.getValue());
}

There should not be a high demand for this particular conversion since you would normally use a 'foreach' loop in C#, which would convert more cleanly to Java.

like image 32
Dave Doknjas Avatar answered Oct 26 '25 05:10

Dave Doknjas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!