Java 具有ArrayList值的HashMap在Get()调用时返回Null
我有一个HashMap,它存储我创建的一个对象作为键,并映射到类似对象的ArrayList 但是,我正在调用get方法,使用jGrasp的调试器,我可以清楚地看到我在get中使用的键存在,并且确实映射到数组,但是我能得到的唯一值是null值 这里是我得到空值的地方 Entry是一个包装器类,默认为其内部对象的equals方法Java 具有ArrayList值的HashMap在Get()调用时返回Null,java,arraylist,Java,Arraylist,我有一个HashMap,它存储我创建的一个对象作为键,并映射到类似对象的ArrayList 但是,我正在调用get方法,使用jGrasp的调试器,我可以清楚地看到我在get中使用的键存在,并且确实映射到数组,但是我能得到的唯一值是null值 这里是我得到空值的地方 Entry是一个包装器类,默认为其内部对象的equals方法 public boolean equals(Object o){ if(o == null){ return false; }
public boolean equals(Object o){
if(o == null){
return false;
}
else if(o instanceof Record){
Record r = (Record) o;
return this.entity.equals(r.entity) && this.relation.equals(r.relation) && this.property.equals(r.property);
}
else return false;
}
我这里还有一个为对象编写的哈希代码
int h = 0;
public int hashCode() {
int hash = h;
if(h != 0)
return hash;
String len = entity.concat(relation.concat(property));
for(int i = 0; i < len.length(); i++)
hash = hash * 31 +(int)len.charAt(i);
return hash;
}
我的HashMap中出现了一些冲突,但我知道这不应该是一个太大的问题。有什么想法吗
public boolean equals(Object o){
if(o == null){
return false;
}
else if(o instanceof Record){
Record r = (Record) o;
return this.entity.equals(r.entity) && this.relation.equals(r.relation) && this.property.equals(r.property);
}
else return false;
}
您的Entry equals方法可能有一些问题,关系的定义是什么?
关系必须是overwrite equals和hashCode
把你所有的代码都放在这里很好,你的main定义是什么?
在你的代码中有很多地方可能包含空指针错误Entry类的equals方法实现是什么?o instanceof Record o永远不会是instance Record,它通过参数而不是Record接收并输入oobject你能发布你的整个Entry类吗,通过传入records equals方法并严格比较两个对象的记录,我不是绕过了这个问题吗?也许我误解了你。既然你在那里授权了相等,那么记录下的相等和hashcode方法是什么呢?
int h = 0;
public int hashCode() {
int hash = h;
if(h != 0)
return hash;
String len = entity.concat(relation.concat(property));
for(int i = 0; i < len.length(); i++)
hash = hash * 31 +(int)len.charAt(i);
return hash;
}
private static class Entry {
private static boolean active;
private Record rec;
public Entry(Record r){
this.rec = r;
this.active = true;
}
public String entity() {
return rec.entity;
}
public String relation() {
return rec.relation;
}
public String property() {
return rec.property;
}
public Record record(){
return this.rec;
}
public boolean isActive(){
return this.active;
}
public void deactivate(){
this.active = false;
}
public void activate(){
this.active = true;
}
public boolean equals(Entry e) {
return this.rec.equals(e.record());
}
public int hashCode() {
return this.rec.hashCode();
}
public String toString() {
return rec.toString();
}
}
public boolean equals(Object o){
if(o == null){
return false;
}
else if(o instanceof Record){
Record r = (Record) o;
return this.entity.equals(r.entity) && this.relation.equals(r.relation) && this.property.equals(r.property);
}
else return false;
}