Mayur Kharche
Mayur Kharche

Reputation: 717

Remove duplicates from ArrayList<CustomClass> Android

I just able to load songs from sdcard and get a list of their albums but it contains duplicates in it. How to remove duplicated from my album list. My Album list is a type of ArrayList and Album class contains two String variable in it. thank you for your help.

Upvotes: 1

Views: 1407

Answers (1)

petey
petey

Reputation: 17140

For your Custom class, add an equals and hashCode method,

public static class Custom
{
    public final String item1;
    public final String item2;
    public Custom(String i1, String i2) {
        item1 = i1;
        item2 = i2;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        Custom custom = (Custom) o;

        if (!item1.equals(custom.item1)) {
            return false;
        }
        if (!item2.equals(custom.item2)) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int result = item1.hashCode();
        result = 31 * result + item2.hashCode();
        return result;
    }

}

Then before adding, check that the Arraylist does not contain a Custom before adding.

final ArrayList<Custom> customs = new ArrayList<Custom>();
Custom one = new Custom("aa", "bb");
Custom two = new Custom("aa", "bb");

if (!customs.contains(one)) {
    arraylist.add(one);
}

if (!customs.contains(two)) {
    arraylist.add(two);
}

Upvotes: 3

Related Questions