当使用一个类作为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;
}
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getType() {
return type;
}
return type;
}
public void setType(Integer type) {
this.type =type;
}
public Integer getCode() {
return code;
}
return code;
}
public void setCode(String code) {
this.code =code;
}
public Integer getName() {
return name;
}
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;
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;
}
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:
- The key needs to implement
.equals()
and.hashCode()
correctly - The key must not be changed in any way that changes it's
.hashCode()
value while it's used as the key - Ideally any object used as a key in a
HashMap
should be immutable. This would automatically ensure that 2. is always held true. - Objects that could otherwise be GCed might be kept around when they are used as key and/or value.