I have an implementation of a hashMap. When calling the get() function, which returns the associated value of the input key, if it exists, iterates through the map to see if it can find an entry with a key that are equivalent to the input and also share the same hashcode. If so, it returns the associated value.
I learned that the error is occurring somewhere in a helper method branching from my put(Object K, Object V) function.
public V put(K key, V value) {
System.out.print("KEY at PUT IS " + key);
if (key == null) {
...
return null;
}
int hash = key.hashCode();
int bucket = hash(hash, table.length);
System.out.println("Key is " + key + "bucket is " + bucket + "hash is " + hash);
...
add(hash, key, value, bucket);
return null;
}
The relevant part of the helper function is as follows.
private void add(int hash, K key, V val, int bucket) {
Entry<K, V> e = table[bucket];
System.out.println("table[bucket] before adding a value is " + table[bucket]);
System.out.println("key in ADD is " + key + "HASH in ADD " + hash);
table[bucket] = new Entry<K, V>(key, val, e);
size++;
System.out.println(" table[bucket] is now " + table[bucket].key + " table[bucket] hash is now" + table[bucket].hashCode());
...
}
Now, if i create a new hashMap, x, and call x.put("foo", 2); the following is printed.
PUTTING 2
...
(we reach the add function)
table[bucket] before adding a value is null
Key in ADD is foo, HASH in ADD 101574
table[bucket] is now foo, table[bucket] hash is now 3149757
My assumption is that it has something to do with how I am inputting the new entry. However, a new entry is simply instantiated with a key, value, and "next" item. So, after a long time debugging I cannot understand how the hashCode changed from 101574 to 3149757.
I read this question to see that inserting data can alter a previous hashCode.
when add key-value pair to a hashMap, why Java makes hashMap's hashCode change?
However, i have seen several implementations where this does not appear to be an issue. Shouldn't this hashCode remain the same?