I would like to know of a Map that works like a regular HashMap/Hashtable except it takes a function which returns the hashcode and performs the equality test rather than letting the HashMap use Object.hashCode/equals.
I cant use TreeMap because the objects do not implement Comparable and there is no stable way to handle the case of unequal objects. One cannot use System.identityHashCode because there is the potential for conflicts for objects that are not equal.
Ideally it would be great if the Map took a function in a similar way one can supply a custom Comparator to a TreeMap rather than letting the TreeMap cast parameters to Comparable.
The only way around this problem is to wrap each key and have the wrapper do the custom hashing/equals but surely therse a better way.
HashMap uses multiple buckets and each bucket points to a Singly Linked List where the entries (nodes) are stored. Once the bucket is identified by the hash function using hashcode, then hashCode is used to check if there is already a key with the same hashCode or not in the bucket(singly linked list).
In Java, one of the most basic computer science concepts is “hashing”. Java's hashCode() function does the hashing for us. By employing hashing techniques, it is possible to map data to a representational integer value. A hash code in Java is an integer number associated with every object.
The idea is to make each cell of hash table point to a linked list of records that have same hash function value. Let's create a hash function, such that our hash table has 'N' number of buckets. To insert a node into the hash table, we need to find the hash index for the given key.
HashMap is a part of the Java collection framework. It uses a technique called Hashing. It implements the map interface. It stores the data in the pair of Key and Value. HashMap contains an array of the nodes, and the node is represented as a class.
Did you consider a simple wrapper around the objects you would like to cache?
class Wrapper {
YourObject object;
public boolean equals(Object someOther) {
...
}
public int hashCode() {
}
}
As other answers suggest wrapping your objects with an object with the desired hashCode and equals is generally the best way to go. If on the rare case you want the function to be to use the original equals and hashCode implementation on Object there actually is IdentityHashMap for that very use case. However I appreciate the function you want is likely something than this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With