如何从Iterator获取两个连续值 [英] how can i get two consecutive values from Iterator

查看:245
本文介绍了如何从Iterator获取两个连续值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,我试图获得Iterator的两个连续元素。

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);
    }
}

但我仍然得到x和Y相同的值。

But still i am getting same values for x and Y.

这有什么问题,我得到两个变量x和y的相同值。

What is wrong with this, i am getting the same value for the two variables x and y.

推荐答案

最终的问题是语句。您的代码不只是从迭代器中获取前两个元素。相反,如果Iterator中有偶数个元素,它将获取最后两个元素。如果有一个奇数个元素,那么你将获得相同的x和y 值。具体来说,是最后一个元素。

The ultimate problem is with the while statement. 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.

更基本的是,您的代码的问题是 u v x y 在您的方法之外声明。我假设你这样做是因为你不知道如何返回多个值。如果需要返回多个值,则返回一个元素数组,或返回一个自定义容器类。

More fundamentally, the problem with your code is u, v, x and y are 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:

public static Value[] nextTwo(Iterator<Value> values) {
    return new Value[] {
        (values.hasNext()?values.next():null),  
        (values.hasNext()?values.next():null)
    };
}

请注意,返回数组的第二个元素是 null 如果Iterator只剩下一个值。如果Iterator为空,则数组的两个元素都将是 null

Note that the second element of the returned array will be null if the Iterator only has one value left in it. Both elements of the array will be null if the Iterator is empty.

这篇关于如何从Iterator获取两个连续值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆