Reputation: 30097
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
.
Upvotes: 4
Views: 4490
Reputation: 198033
This sounds like Guava's PeekingIterator
; you can decorate a plain Iterator
with Iterators.peekingIterator
.
Upvotes: 3
Reputation: 6542
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.
Upvotes: 1
Reputation: 2549
If you use a standard concrete Collection class, such as HashSet
and ArrayList
to name but two, you will have access to an iterator.
Calling the method: collection.hasNext()
will return a boolean, but not advance the pointer. This will allow you to determine whether you should attempt to read collection.next()
.
Example:
Set<String> numbers = new HashSet<>();
// fill in set...
while (numbers.hasNext()) {
System.out.println(numbers.next());
}
Of course, you can also iterate through a collection using the for-each syntax:
for (String s : numbers) {
System.out.println(s)
}
Upvotes: -1