2013-01-18 109 views
1

我需要比较两个不同大小的Arraylists。比较两个阵列列表和迭代器

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

第二个循环只迭代一次而不是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(); 
} 
+1

您似乎误解了如何使用迭代器。如果你使用迭代器,你不需要调用'String ID = list.get(i).ID();',你只需调用:'String ID = it.next()。ID();'。 – assylias

+0

*我需要比较*的一些更多细节将会有所帮助。你想检查它们是否包含相同的对象*或者它们是否在相同的位置包含相同的对象*。 –

+0

如果您正在使用现代编程IDE(如eclipse),请开始使用自动格式化。在阅读此代码后,我将不得不再次与我的医生签署一份协议:P – brimborium

回答

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 
    } 
    } 
} 
2

您需要实例迭代器oit例如每次迭代

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

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

1

什么

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

你需要调整你的对象的equals方法来比较正确的东西(在你的榜样的ID)。

+0

他需要重写'equal()',因为他正在检查相同的'ID()'而不是相同的实例。如果你添加这个,这个答案会非常好。 (虽然OP提到他**有**使用迭代器 - 出于任何原因。) – brimborium

+0

谢谢你的注意。我误解了,我得到了这样的一句话:“我可以用两个循环来完成它,但我很失望,除了使用迭代器之外,我不知道任何其他解决方案”。 – Danstahr

+0

你的解决方案非常好,我会把它留在这里,但我想它不能解决OP的问题。 – brimborium

1
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() )。