Vincent Mercado Sy
Vincent Mercado Sy

Reputation: 45

Java Comparing Fields by Iteration of (N) Number of Objects

Can you help me with this one?

I'm trying to compare fields from a list of (n) number objects.

To be clearer, here is an example.

   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

Question is, how can I cater to iterate any (n) number of objects in a list?

Upvotes: 1

Views: 45

Answers (1)

Eran
Eran

Reputation: 393936

It looks like what you want is to compare all pairs of elements from the List and do something if at least one pair has different IDs :

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
}

Upvotes: 1

Related Questions