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.
equals
function. Why do you think that char[]
has an overridden equals
that allows it to compare itself with Strings properly? Or even between each other? It does not override equals, and will only return true if it's the same instance.As per your comment I understand that you want to be able to edit the string. That's fine before you put it into the map. But do not change objects when they are keys in a map in a way that might change the hash code or equals. Best way to do this is to use a custom object. Arrays are not suitable for this.
If you really want to change the values on the fly while they're in a map - use a BiMap
(or do what it does in forcePut
yourself).