我只能从 SD 卡加载歌曲并获取他们的专辑列表,但其中包含重复项。如何从我的相册列表中删除重复项。我的 Album 列表是 ArrayList 的一种类型,Album 类中包含两个 String 变量。 谢谢你的帮助。
最佳答案
为您的自定义类添加一个 equals 和 hashCode 方法,
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;
}
}
然后在添加之前,先检查Arraylist中不包含Custom再添加。
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);
}
关于android - 从 ArrayList<CustomClass> Android 中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31788615/