如何检查哈希表中的键是否具有某个哈希码?

时间:2021-04-14 07:28:21

For example, ht.put("A", 0); has a hashcode of 65. How would I search the hashtable to see whether a key with a hashcode of 65 exists?

例如,ht.put(“A”,0);哈希码是65.如何搜索哈希表以查看哈希码为65的密钥是否存在?

2 个解决方案

#1


1  

You can construct a class whose hashcode is the code in question:

您可以构造一个类,其哈希码是有问题的代码:

public class HashCodeWrapper {
    private final int hashCode;
    public HashCodeWrapper(int hashCode){
        this.hashCode = hashCode;
    }
    @Override
    public int hashCode(){
        return hashCode;
    }
    @Override
    public boolean equals(Object o){ return this.hashCode == o.hashCode(); }
}

You can then pass this into Hashtable#get(Object).

然后,您可以将其传递给Hashtable#get(Object)。

Note that there may be hash collisions, in this case the result will be any with this hashcode. However, with a null-check this is more than enough to check for the existence of this hashcode.

请注意,可能存在哈希冲突,在这种情况下,结果将是具有此哈希码的任何哈希冲突。但是,使用空检查,这足以检查是否存在此哈希码。

#2


0  

To achieve that, you have to traverse map's entrySet() and check each key()'s hashCode() against some value you want to check presense, 65 in your example:

要实现这一点,你必须遍历map的entrySet()并检查每个key()的hashCode()与你想要检查presense的值,在你的例子中为65:

Map<String, String> map = new HashMap<String, String>();

public boolean hashCodePresent(int hashCode) {
    for (Map.Entry<String, String> mapEntry : map.entrySet()) {
        if (mapEntry.getKey().hashCode() == hashCode) {
            return true;
        }
    }

    return false;
}

#1


1  

You can construct a class whose hashcode is the code in question:

您可以构造一个类,其哈希码是有问题的代码:

public class HashCodeWrapper {
    private final int hashCode;
    public HashCodeWrapper(int hashCode){
        this.hashCode = hashCode;
    }
    @Override
    public int hashCode(){
        return hashCode;
    }
    @Override
    public boolean equals(Object o){ return this.hashCode == o.hashCode(); }
}

You can then pass this into Hashtable#get(Object).

然后,您可以将其传递给Hashtable#get(Object)。

Note that there may be hash collisions, in this case the result will be any with this hashcode. However, with a null-check this is more than enough to check for the existence of this hashcode.

请注意,可能存在哈希冲突,在这种情况下,结果将是具有此哈希码的任何哈希冲突。但是,使用空检查,这足以检查是否存在此哈希码。

#2


0  

To achieve that, you have to traverse map's entrySet() and check each key()'s hashCode() against some value you want to check presense, 65 in your example:

要实现这一点,你必须遍历map的entrySet()并检查每个key()的hashCode()与你想要检查presense的值,在你的例子中为65:

Map<String, String> map = new HashMap<String, String>();

public boolean hashCodePresent(int hashCode) {
    for (Map.Entry<String, String> mapEntry : map.entrySet()) {
        if (mapEntry.getKey().hashCode() == hashCode) {
            return true;
        }
    }

    return false;
}