gpt4 book ai didi

java - 比较Java中的两个对象

转载 作者:行者123 更新时间:2023-11-29 09:38:03 26 4
gpt4 key购买 nike

我有同一个实体“社区”的两个不同对象

并且两个对象(community 和 com)具有相同的值

Communty.java 有以下变量:

   private Integer communityId;
private String communityName;
private String description;

// many to many relationship
private Set<Faculty> faculties = new HashSet<Faculty>();
private Set<User> users = new HashSet<User>();

我使用了 equal 方法:

@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if(obj==null)
return false;
if(obj==this)
return true;
if(!(obj instanceof Community)) return false;

Community community = (Community)obj;
return community.getCommunityId() == this.getCommunityId();
}

当我检查 community==com 时,它返回 false .. 为什么?我犯了什么错误?这两个对象都是从数据库中检索的!

最佳答案

== 比较指向对象的链接。

您应该显式调用 community.equals(com)。还要注意 null 检查。

关于java - 比较Java中的两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14053844/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com