有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法通过一个键从hashmap获取对象,该键具有相同的hashcode,并且两个键等于()

我试图完成一项任务,在我的哈希映射中,我只存储实际数据正在堆外存储的KV代理对象

因此,我创建了一个代理对象,它覆盖equalshashcode方法,使其与原始对象具有相同的值

然后我测试结果,发现我无法通过原点键再次找到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

输出如下所示:

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

在我看来,hashcode是为了找到bucket位置,它们将使用equals来确定它们是否相等,既然hashcode是相同的,它们是相等的(),为什么呢

供参考:

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!!!!

但是,由于我不知道如何更改密钥,它们来自用户,我如何解决它


共 (0) 个答案