Possible Duplicate:
How to most elegantly iterate through parallel collections?
Is there an accepted Java equivalent to Python's zip()?
我必须同时遍历两个对象集合,看看它们的成员是否相等。有没有办法使用计数器来访问对象或执行类似于下面的 for 循环的操作?
Boolean compareCollection(Collection<Object> c1, Collection<Object> c2)
{
//something like -
for (Object ob1 : c1, Object ob2 : c2){
//check if ob1.val == ob2.val
}
return true;
}
像这样:
public static boolean compareCollection(Collection<Object> c1, Collection<Object> c2) {
if (c1 == null)
return c2 == null;
else if (c2 == null || c1.size() != c2.size())
return false;
Iterator<Object> it1 = c1.iterator();
Iterator<Object> it2 = c2.iterator();
while (it1.hasNext()) {
Object o1 = it1.next();
Object o2 = it2.next();
if (!o1.equals(o2))
return false;
}
return true;
}
当然,您必须使用正确的类型(我猜这不仅仅是 Object
)对集合进行参数化并进行适当的比较:
if (!o1.val.equals(o2.val))