【问题标题】:Compare two arraylists with iterators用迭代器比较两个数组列表
【发布时间】:2013-01-02 01:25:39
【问题描述】:

我需要比较两个不同大小的Arraylist。

我可以用两个循环来做到这一点 - 但我需要使用迭代器。

第二个循环只迭代一次而不是n次。

while (it.hasNext()) {
    String ID = (String) Order.get(i).ID();
    j = 0;              
    while (o.hasNext()) {   
        String Order = (String) Order.get(j).ID();
        if (myOrder.equals(Order)) {
            //do sth
        }
        j++;
        o.next();
    }
    i++;
    it.next();
}

【问题讨论】:

  • 您似乎误解了如何使用迭代器。如果使用迭代器,则无需调用String ID = list.get(i).ID();,只需调用:String ID = it.next().ID();
  • 更多关于我需要比较的细节会有所帮助。您要检查它们是否包含相同的对象,或者它们是否在相同的插槽中包含相同的对象
  • 如果您正在使用现代编程 IDE(如 eclipse),请开始使用自动格式化。阅读此代码后,由于眼癌,我将不得不与我的医生再次预约...:P
  • 另外,您应该尝试关注Java Naming Conventions。因此,方法名应该以小写开头(id(),而不是ID())和变量名(String order;,而不是String Order;)。这将优化可读性并防止代码出现令人讨厌的问题。

标签: java arraylist iterator while-loop


【解决方案1】:

您需要为 it 的每次迭代实例化迭代器 o,例如

while (it.hasNext()) {
   Iterator<String> o = ...
   while (o.hasNext()) {
     // ...
   }
}

铌。你不需要索引变量j。您只需调用o.next() 即可获取迭代器引用的列表元素。

【讨论】:

    【解决方案2】:

    怎么样

    List<String> areInBoth = new ArrayList(list1);
    areInBoth.retainAll(list2);
    for (String s : areInBoth)
        doSomething();
    

    您需要调整对象的 equals 方法以比较正确的内容(示例中的 ID)。

    【讨论】:

    • 他需要覆盖equal(),因为他正在检查相同的ID(),而不是相同的实例。如果你加上这个,这个答案会很好。 (尽管 OP 提到他 必须 使用迭代器 - 无论出于何种原因。)
    • 感谢您的关注。我误解了,我得到了这样的句子“我可以使用两个循环来完成,但我很失望我不知道除了使用迭代器之外的任何其他解决方案”。
    • 你的解决方案非常好,我会留在这里,虽然我猜它并不能解决 OP 的问题。
    【解决方案3】:

    您可以以比您更简单的方式使用迭代器:

    Iterator<YourThing> firstIt = firstList.iterator();
    while (firstIt.hasNext()) {
      String str1 = (String) firstIt.next().ID();
      // recreate iterator for second list
      Iterator<YourThing> secondIt = secondList.iterator();
      while (secondIt.hasNext()) {
        String str2 = (String) secondIt.next().ID();
        if (str1.equals(str2)) {
          //do sth
        }
      }
    }
    

    【讨论】:

      【解决方案4】:
      Iterator<Object> it = list1.iterator();
      while (it.hasNext()) {
          Object object = it.next();
          Iterator<Object> o = list2.iterator();
          while (o.hasNext()) {   
              Object other = o.next();
              if (object.equals(other)) {
                  //do sth
              }
          }
      }
      

      两个iterators 因为有两个列表,获取每个object 并检查下一个并获取下一个项目(hasNext()next())。

      【讨论】:

        猜你喜欢
        • 2021-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-05
        • 2016-12-11
        • 1970-01-01
        • 1970-01-01
        • 2017-12-23
        相关资源
        最近更新 更多