java - 数组列表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
解决方案
- 不要忘记实现哈希码。
- 对于字符串,使用 equals(或 !equals)而不是 ==(或 !=)
- 也可以将等号的最后 3 行更改为
return (folderName.equals(other.folderName) && stickerName.equals( other.stickerName)
:
推荐阅读
- express - 使用 Postman 测试请求未定义
- c# - 在目录 C# 中查找游戏启动器可执行文件
- c++ - 是否可以回调模板类的成员?
- amazon-web-services - 使用 Terraform 在 AWS 中创建 Lambda 函数时无法加载文件名
- javascript - react-modal 的奇怪行为
- apache-spark - 用于 Spark Streaming 的 Kafka 连接器版本
- python-3.x - 使用 from_logs 生成器删除某个月份的所有消息
- r - 如何从字母向量中枚举字符串
- excel - 如何使用 VB.net 读取作为 COM__Object 传递的自定义 VBA 类对象的成员?(UIPath)
- linux - Kubernetes 工作节点 cpu 和内存请求始终保持为零