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?Selvin– Selvin2015-08-03 13:39:03 +00:00Commented 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 ...Selvin– Selvin2015-08-03 13:40:16 +00:00Commented 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.Mayur Kharche– Mayur Kharche2015-08-03 15:28:20 +00:00Commented 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 ...Selvin– Selvin2015-08-03 15:34:37 +00:00Commented Aug 3, 2015 at 15:34
Add a comment
|
1 Answer
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);
}