首页 > 解决方案 > 数组列表list.contain() 不起作用并返回 false?

问题描述

这个问题在stackoverflow中问了很多次,我尝试了所有大师的答案。但是 list.contain() 总是返回 false。并且还覆盖了 equal() 方法。

这是我的 pojo 课

public class RecentStickerPojo
{
    File stickerName;
    File folderName;

@Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        RecentStickerPojo other = (RecentStickerPojo) obj;
        if (folderName != other.folderName&&stickerName!=other.stickerName)
            return false;
        return true;
    }
}

在活动课上

RecentStickerPojo recentStickerPojo=new RecentStickerPojo();
recentStickerPojo.setStickerName(s1);
recentStickerPojo.setFolderName(f1);
list.contains(recentStickerPojo) // return false

标签: javaandroid

解决方案


  1. 不要忘记实现哈希码。
  2. 对于字符串,使用 equals(或 !equals)而不是 ==(或 !=)
  3. 也可以将等号的最后 3 行更改为 return (folderName.equals(other.folderName) && stickerName.equals( other.stickerName)

推荐阅读