Java通过迭代(N)对象比较字段

时间:2015-11-29 20:41:44

标签: java arraylist iteration

你能帮我解决这个问题吗?

我正在尝试比较(n)个数字对象列表中的字段。

为了更清楚,这是一个例子。

   ArrayList<TestObjectType> listOfObjects = new ArrayList<TestObjectType>();
    TestObjectType itemA = new TestObjectType();
    itemA.setID(1);
    TestObjectType itemB = new TestObjectType();
    itemA.setID(2);
    TestObjectType itemC = new TestObjectType();
    itemA.setID(3);

    //do compare here
    if (2 == listOfObjects.size())
    {   TestObjectType itemA = listOfObjects.get(0);
        TestObjectType itemB = listOfObjects.get(1);
        if (itemA.getID != itemB.getID)
        {   //do something here
            ;
        }
    } 
    else if (3 == listOfObjects.size())
    {   TestObjectType itemA = listOfObjects.get(0);
        TestObjectType itemB = listOfObjects.get(1);
        TestObjectType itemC = listOfObjects.get(2);
        if ((itemA.getID != itemB.getID) || 
            (itemA.getID != itemC.getID) || 
            (itemB.getID != itemC.getID))
        {   //do something here
            ;
        }
    }
    // so on and so forth until all (n) number of objects has been compared

问题是,我怎样才能满足迭代列表中任意(n)个对象的数量?

1 个答案:

答案 0 :(得分:1)

看起来你想要的是比较List中的所有元素对,并且如果至少有一对具有不同的ID,则执行一些操作:

boolean found = false;
for (int i = 0; i < listOfObjects.size() && !found; i++) {
    for (int j = i+1; j < listOfObjects.size() && !found; j++) {
        if (listOfObjects.get(i).getID != listOfObjects.get(j).getID)
            found = true;
    }
}
if (found) {
    // do something
}