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.
Asked
Active
Viewed 1,401 times
1
-
possible duplicate of [How do I remove repeated elements from ArrayList?](http://stackoverflow.com/questions/203984/how-do-i-remove-repeated-elements-from-arraylist) – Selvin Aug 03 '15 at 13:39
-
... and of course ... it will not work ... obviously, it need one more thing ... something that would compare the items ... – Selvin Aug 03 '15 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. – Mayur Kharche Aug 03 '15 at 15:28
-
It is a duplicate ... but still you should know how Set compare the objects ... so take a look @petey answer ... – Selvin Aug 03 '15 at 15:34
1 Answers
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);
}

petey
- 16,914
- 6
- 65
- 97
-
-
I can't ... I already know this ... and ... i didn't ask... :P ... ok, at least i could upvote :P – Selvin Aug 03 '15 at 15:32