Here is my code that i tried to get two consecutive elements of Iterator.
public void Test(Iterator<Value> values) {
Iterator<Value> tr = values;
while (tr.hasNext()) {
v = tr.next();
x = v.index1;
// u = null;
if (tr.hasNext()) {
u = tr.next();
y = u.index1;
} else {
u = v;
y = u.index1;
}
System.out.println(x);
System.out.println(y);
}
}
But still i am getting same values for x and Y.
What is wrong with this, i am getting the same value for the two variables x and y.
The ultimate problem is with the
whilestatement. Your code will not just grab the first two elements from the Iterator. Rather, if there is an even number of elements in the Iterator, it’ll grab the last two. If there’s an odd number of elements then you’ll get the same value for x and y. Specifically, the last element.More fundamentally, the problem with your code is
u,v,xandyare declared outside of your method. I assume you’re doing this because you don’t know how to return more than one value. If you need to return multiple values, return an array of elements, or return a custom container class.Here’s an example of how you can return in an array the two elements taken off of a given Iterator:
Note that the second element of the returned array will be
nullif the Iterator only has one value left in it. Both elements of the array will benullif the Iterator is empty.