您的位置:首页 > 其它

使用一个类作为hashMap的key

2013-07-22 16:00 274 查看
当使用一个类作为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:

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐