从 ArrayList<CustomClass> Android 中删除重复项
Remove duplicates from ArrayList<CustomClass> Android
我只能从 SD 卡加载歌曲并获取他们的专辑列表,但其中包含重复项。如何从我的相册列表中删除重复项。我的专辑列表是一种 ArrayList 类型,专辑 class 包含两个字符串变量。
谢谢你的帮助。
对于您的自定义 class,添加一个 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);
}
我只能从 SD 卡加载歌曲并获取他们的专辑列表,但其中包含重复项。如何从我的相册列表中删除重复项。我的专辑列表是一种 ArrayList 类型,专辑 class 包含两个字符串变量。 谢谢你的帮助。
对于您的自定义 class,添加一个 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);
}