How to compare two different list object in java?

后端 未结 2 557
猫巷女王i
猫巷女王i 2020-12-20 09:16

I have two class lists like List A1 and List b1 and both lists contain one field which is common. So by using this fiel

相关标签:
2条回答
  • 2020-12-20 09:35

    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);
            if (aClass.commonField != bClass.commonField) return false;
        }
        return true;
    }
    

    Both lists should be sorted by that commonField field

    0 讨论(0)
  • 2020-12-20 09:42

    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 讨论(0)
提交回复
热议问题