After doing research and looking up old posts for a while I realize that when you use a Hashmap or Hashtable in Java where Strings are the keys, the first "round" of hashing is applied to each String objects hashCode (apparently there is a second hash function that is applied to the result of int hashCode()
), where by default int hashCode()
has some relationship with it's callers location in memory (from what I read). With that being said, if I had a map with a developer defined class for keys, I read that I can override int hashCode()
and use some distinct field(s) of my object to return the most unique int possible for each object. However, consider the code fragment below that contains arrays of primitive types.
import java.util.HashMap;
public class test
{
public static void main(String[] args) {
HashMap<char[], int[] > map = new HashMap<char[], int[]>();
String s = "Hello, World";
int x[] = { 1, 2, 3, 4, 5 };
map.put( s.toCharArray(), x );
x = map.get( s );
for ( int i : x )
System.out.print( i );
}
}
The program crashes from a NullPointerException
of course because map.get( s );
returns null. I suspect that has happened because there are two different references between map.put()
and map.get()
. What I want the program to output is 1 2 3 4 5.
My question: How can I get the above code fragment to look up the keys by the value of the key vs the reference of the key? That is, how can I get the program to output 1 2 3 4 5?
Edit: I am using the hashmap as a look up table. I am reading strings from a file and need a fast way to determine if the string I just read in is in the table or not.