开发者

How to compare two different list object in java?

开发者 https://www.devze.com 2023-02-16 05:06 出处:网络
I have two class lists like List<Aclass> A1 and List<Bclass> b1 and both lists contain one field which is common. So by using this field I have to compare those two list? Please can anyone

I have two class lists like List<Aclass> A1 and List<Bclass> b1 and both lists contain one field which is common. So by using this field I have to compare those two list? Please can anyone help me? Be en开发者_JAVA百科sure that those class lists are different.


I'm not sure I fully understand the question, but you're asking for something like this?

public boolean compare (List<AClass> listA, List<BClass> listB) {
    if (listA.size() != listB.size ()) {
         return false;
    }

    for (int i=0; i<listA.size(); i++) {
        AClass aClass = (AClass) listA.get(i);
        BClass bClass = (BClass) listB.get(i);

        // This is example for numeric comparison
        // For String, use !equals()
        if (aClass.commonField != bClass.commonField) return false;
    }

    return true;
}

Both lists should be sorted by that commonField field


Checkout the javadoc for List.equals():

two lists are defined to be equal if they contain the same elements in the same order.

The equals method can be used here and of course ignores the generic types you have declared the two lists to be. The equals method for AbstractList (which ArrayList and a bunch of other list classes implements) will iterate over both lists and call equals on each of the elements in order, once done it makes sure there aren't any items left in either list.

Given all this, you will be able to call the equals method to determine weather two lists contain the same elements:

List<Aclass> A1 = new ArrayList<Aclass>();
List<Bclass> b1 = new ArrayList<Bclass>();

// getElement returns a private field that can be cast to both Aclass and Bclass
A1.add(getElement());
b1.add(getElement());

if (A1.equals(b1)) {
    System.out.println("two lists are equal");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消