Reputation:
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?
Upvotes: 0
Views: 221
Reputation: 6533
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<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;
}
Upvotes: 0
Reputation: 41271
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)
.
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.
Upvotes: 1