How to find duplicates in an ArrayList<Object>?

后端 未结 4 1633
轮回少年
轮回少年 2020-12-25 08:54

This is a pretty common question, but I could not find this part:

Say I have this array list:

List arrayList = new List

        
4条回答
  •  猫巷女王i
    2020-12-25 09:12

    I'd suggest that you override both equals and hashCode (HashSet relies on both!)

    To remove the duplicates you could simply create a new HashSet with the ArrayList as argument, and then clear the ArrayList and put back the elements stored in the HashSet.

    class MyDataClass {
        String name;
        String age;
    
        @Override
        public int hashCode() {
            return name.hashCode() ^ age.hashCode();
        }
    
        @Override
        public boolean equals(Object obj) {
            if (!(obj instanceof MyDataClass))
                return false;
    
            MyDataClass mdc = (MyDataClass) obj;
            return mdc.name.equals(name) && mdc.age.equals(age);
        }
    }
    

    And then do

    List arrayList = new ArrayList();
    
    Set uniqueElements = new HashSet(arrayList);
    arrayList.clear();
    arrayList.addAll(uniqueElements);
    

    But, what if I do not have the luxury of doing that?

    Then I'd suggest you do some sort of decorator-class that does provide these methods.

    class MyDataClassDecorator {
    
        MyDataClass mdc;
    
        public MyDataClassDecorator(MyDataClass mdc) {
            this.mdc = mdc;
        }
    
        @Override
        public int hashCode() {
            return mdc.name.hashCode() ^ mdc.age.hashCode();
        }
    
        @Override
        public boolean equals(Object obj) {
            if (!(obj instanceof MyDataClassDecorator))
                return false;
    
            MyDataClassDecorator mdcd = (MyDataClassDecorator) obj;
            return mdcd.mdc.name.equals(mdc.name) && mdcd.mdc.age.equals(mdc.age);
        }
    }
    

提交回复
热议问题