android - 从 ArrayList<CustomClass> Android 中删除重复项

标签 android listview arraylist duplicates

我只能从 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/

相关文章:

android - 为 RecyclerView 下载图片时出现性能问题

java - Listview 中的内容是不可见的

android - 第二次设置适配器时不显示 ListView

Java:如何修复此 NPE?

android - 当我将图像放入可绘制文件夹时,为什么 BitmapFactory.decodeResource() 会变慢?

java - 如何从另一个类访问 hashmap 值?

程序中出现java.util.ConcurrentModificationException

java - 通过 JTable 从 ArrayList 中删除项目

java - 安卓 IllegalArgumentException lockCanvas()

android - 根据设备创建将打开网站、iOS、Android 或 Win8 应用程序的 Web 链接