[英]Compare two arraylists with iterators
我需要比較兩個不同大小的不同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();
}
您可以使用比您簡單得多的方式使用迭代器:
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
}
}
}
您需要實例迭代器o
為每個迭代it
如
while (it.hasNext()) {
Iterator<String> o = ...
while (o.hasNext()) {
// ...
}
}
Nb。 您不需要索引變量j
。 您只需調用o.next()
即可獲得迭代器引用的列表元素。
關於什么
List<String> areInBoth = new ArrayList(list1);
areInBoth.retainAll(list2);
for (String s : areInBoth)
doSomething();
您需要調整對象的equals方法以比較正確的內容(示例中的ID)。
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
和下一個object
(具有hasNext()
和next()
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.