1

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.

4
  • possible duplicate of How do I remove repeated elements from ArrayList? Commented Aug 3, 2015 at 13:39
  • ... and of course ... it will not work ... obviously, it need one more thing ... something that would compare the items ... Commented Aug 3, 2015 at 13:40
  • It,s not a duplicate of that question. I can remove elements from ArrayList of predefined classes but my question is to make my list unique using custom class which contain more than one variables. Commented Aug 3, 2015 at 15:28
  • It is a duplicate ... but still you should know how Set compare the objects ... so take a look @petey answer ... Commented Aug 3, 2015 at 15:34

1 Answer 1

3

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

@Selvin if this is working for you, can you accept the answer?
I can't ... I already know this ... and ... i didn't ask... :P ... ok, at least i could upvote :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.