现在的位置: 首页 > 综合 > 正文

使用一个类作为hashMap的key

2013年03月08日 ⁄ 综合 ⁄ 共 1646字 ⁄ 字号 评论关闭
当使用一个类作为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. 

抱歉!评论已关闭.