我正在尝试完成一个任务,在我的哈希映射中,我只存储实际数据存储在堆中的KV代理对象。
所以我创建了一个覆盖equals
和hashcode
方法的代理对象,使其与原始对象具有相同的值。
然后我测试结果并发现我无法通过原点键再次找到V.
ObjectOffHeapProxy offHeapKeyProxy = new ObjectOffHeapProxy(key);
System.out.println("key="+key+"---offHeapKeyProxy.hashCode()==key.hashCode() "+(offHeapKeyProxy.hashCode()==key.hashCode()));
System.out.println("key="+key+"---offHeapKeyProxy.equals(key) "+(offHeapKeyProxy.equals(key)));
ObjectOffHeapProxy offHeapValueProxy = new ObjectOffHeapProxy(value);
skeleton.put(offHeapKeyProxy,offHeapValueProxy);
//put into the map
System.out.println("put by proxy,try get object from the origin key is :" + skeleton.get(key));
//can't find it again.
System.out.println("put by proxy,try get object from the proxy is"+skeleton.get(offHeapKeyProxy));
bloomFilter.add(key.hashCode());
System.out.println("put a proxy,try get object from the proxy is"+skeleton.get(offHeapKeyProxy));
//this works but it does not meet my expectation
OUTPUT就像:
key=1---offHeapKeyProxy.hashCode()==key.hashCode() true
key=1---offHeapKeyProxy.equals(key) true
put a proxy,try get object from the origin key is :null
put a proxy,try get object from the
proxy isxxx.yyy.ObjectOffHeapProxy@b73a019f
在我看来,哈希码是找到存储桶位置,他们将使用equals
来确定它们是否相等,并且由于哈希码是相同的并且它们是等于(),为什么会这样? / p>
供参考:
public class ObjectOffHeapProxy {
private final ByteBuffer buff;
public ObjectOffHeapProxy(Object actual) throws IOException {
byte[] bytes = SerialUtil.serialize(actual);
this.buff = ByteBuffer.allocateDirect(bytes.length);
buff.put(bytes);
}
@Override
public boolean equals(Object o) {
return findActual().equals(o);
}
/**
* actual data's hashcode
* @return
*/
@Override
public int hashCode() {
return findActual().hashCode();
}
public Object findActual() {
try{
buff.flip();
byte[] target = new byte[buff.limit()];
buff.get(target);
return SerialUtil.deserialize(target);//TODO please check
}
catch (IOException | ClassNotFoundException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
}
更新
正如评论指出的那样,等于破坏事物:
System.out.println("key="+key+"---offHeapKeyProxy.hashCode()==key.hashCode() "+(offHeapKeyProxy.hashCode()==key.hashCode()));
System.out.println("key="+key+"---offHeapKeyProxy.equals(key) "+(offHeapKeyProxy.equals(key)));
System.out.println("key="+key+"---key.equals(offHeapKeyProxy) "+(key.equals(offHeapKeyProxy))); //false here!!!!
但由于我不知道要更改密钥,它们来自用户,我该如何解决?