A hash function to handle generic keys

1.1k views Asked by At

Is it possible to write a hash function to handle generic keys or does the type have to be specified? I'm trying to write a hash table for a generic class that stores keys and their value but I'm having a hard time starting.

beanStore stores the values of bean pairs a bean pair is an object of T,N types i.e. it has a parameter of T type and another parameter of N type

public class beanStore<T,N> implements beanFuncs<T,N>{
private Integer cap;

public beanStore(Integer number){cap=number;}

public int hfunc(T key){
//generates hashCode of key 
}

}

And here's the beanFunc class

public interface beanFuncs<T,N> extends Iterable<K>{
public boolean hasKey(T key);
.
.
.
public int size();
public Iterator<T> iterator();
}
1

There are 1 answers

0
Steve P. On

HashMap<K,V> inherently deals with generics. A generic type can take on any object, so what HashMap does is call that object's hashCode().

If you're trying to group multiple types of objects together, you can handle that via generic bounds, ie if you want to have a map that can take objects that are comparable to each other, you can do so via: HashMap<T extends Comparable<T>, K>.

In a more specific case, you can group whatever set of objects that you want to handle and have them implement an interface or extend some superclass.

Long story short, it doesn't make sense to write a hash function for a generic type, let each object handle their own hashCodes. You can't write a generic hash, since hashCode() has a contract with equals(), and it just doesn't make sense to write a generic equals() or hashCode()--these methods should be object specific.