【问题标题】:How to pass content of one iterators to another in Java?如何在 Java 中将一个迭代器的内容传递给另一个迭代器?
【发布时间】:2012-03-13 18:16:57
【问题描述】:

我有两个列表 a = {1,2,2,5,6,6,6,7} 和 b = {2,3,3,6,6,6,8} 我想得到等效的元素,在这种情况下,输出应该是 2 *(2 = 2) 和 9 * (6 = 6) 这是我的代码的一部分

    Iterator aIt = a.iterator();
    Iterator bIt = b.iterator();
    Iterator tempIt = b.iterator();

    int aNode = (Integer)aIt.next();
    int bNode = (Integer)bIt.next();
    Boolean isEquals = false;

    while(aIt.hasNext()||bIt.hasNext()){
        while(aNode<bNode){
            aNode = (Integer)aIt.next();
        }
        while(aNode>bNode){
            bNode = (Integer)bIt.next();
        }
        while(aNode==bNode){
            tempIt = bIt;
            while(aNode==bNode){
                System.out.println(aNode + " = " + bNode);
                bNode = (Integer)tempIt.next();
            }
            aNode = (Integer)aIt.next();
            tempIt = bIt;
            bNode = (Integer)tempIt.next();
            isEquals = true;
        }
        if(isEquals){
            bIt = tempIt;
            isEquals = false;
        }
    }

但是,在我运行代码之后,我意识到我传递的是 bIt 到 tempIt 的引用,而不是内容。如果我真的想使用迭代器来实现这一点,有什么解决方案吗?非常感谢!

【问题讨论】:

  • 不确定我是否理解您如何从 a、b 到 (1,0) (2,0) (4,3) (4,4) (4,5) (5,3) - 您想要进行哪些数据操作?
  • @assylias 这些是索引。仔细阅读。
  • 你能解释一下吗,驱逐者,因为我也不清楚?
  • @deporter 我已经盯着它看了 2 分钟 - 还是不明白...
  • @andrewcooke (1,0) 表示 a[1] = b[0] 等等。收到了吗?

标签: java arraylist iterator


【解决方案1】:

听起来你想克隆你的迭代器,这是 Java 不支持的(clone() 方法是私有的)。 就像注释一样,迭代器不包含数据,您应该将其视为列表的接口。所以也许迭代器不是这里最理想的解决方案。

【讨论】:

  • +1。自己跟踪索引,问题就解决了。
【解决方案2】:

我怀疑有一种更简单的方法可以做到这一点——即,不使用迭代器,而是使用列表本身。

因此,如果您的列表 A 和 B 是 ArrayList&lt;Integer&gt;s,它可能看起来像这样:

public void printMatch(ArrayList<Integer> A, ArrayList<Integer> B) {
    for(int i = 0; i < A.length(); i++) {
        for(int j = 0; j < B.length(); j++) {
            if(A.get(i).equals(B.get(j))) {
                System.out.println("Match!" + A.get(i));
            }
        }
    }
}

或者类似的东西——我没有编译过,但这是正确的想法。

【讨论】:

  • wtf?这只是检测两个列表中是否出现任何值。这不是被问到的(第一个不是修改后的问题)。
猜你喜欢
  • 1970-01-01
  • 2012-10-23
  • 2013-06-17
  • 2023-03-17
  • 2015-09-20
  • 1970-01-01
  • 2015-06-17
  • 1970-01-01
  • 2015-04-15
相关资源
最近更新 更多