使用一个类作为hashMap的key

当使用一个类作为hashMap的key时,需要重写该类的equals()和hashCod()的方法
类的定义代码:

public class Object1{

   private Long id;
   private String code;
   private String name;
   private Integer type;

   public Node(){
   }
       
   public Node(String code,String type){
       this.setCode(code);
       this.setType(type);
   }
   
    public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

       public Integer getType() {
return type;
}


public void setType(Integer type) {
this.type =type;
}
              
       public Integer getCode() {
return code;
}


public void setCode(String code) {
this.code =code;
      
        public Integer getName() {
return name;
}

public void setName(String name) {
this.name =name;
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Object1))
return false;


Node other = (Object1) obj;


if (other.getId() != null && this.getId() != null && other.getId().longValue() == this.getId().longValue()) {
return true;
}


if (other.getType() != null && this.getType() != null && other.getType() != null
&& this.geType() != null
&& other.getCode() == this.getCode()
&& other.getCode() == this.getCode()) {
return true;
}
return false;
}
        @Override
public int hashCode()  {

if(this.getCode() != null && this.getType() != null){
String hashCode = String.valueOf(getType()) + "_" + String.valueOf(getCode());
return hashCode.hashCode();
}

if(id != null){
return id.intValue();
}

return 0;
}

}


小插曲:
question:Using an object as key for a hashmap in Java
google answer:
  1. The key needs to implement .equals() and .hashCode() correctly
  2. The key must not be changed in any way that changes it's .hashCode() value while it's used as the key
  3. Ideally any object used as a key in a HashMap should be immutable. This would automatically ensure that 2. is always held true.
  4. Objects that could otherwise be GCed might be kept around when they are used as key and/or value. 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值