Question

I want to put an object that has been created for a while into a hashmap, and I want it to store according to the current state of the objects.

So I wonder when the hashcode of this object is calculated: when it is created or it is put into the map. And if it is the first situation, how to store the current state.

Thanks a lot.

Edit: I actually mean store it according to the state when insert it into the map. Sorry to mislead.

Was it helpful?

Solution

An object's hashcode is retrieved whenever any code calls the object's hashCode() method (such as a collection, container or any other method).

All the classes inherit a basic hash scheme from the fundamental base class java.lang.Object, but instead many override this to provide a hash function that better handles their specific data. Classes which provide their own implementation must override the object method public int hashCode().

Ref: java hashCode()

OTHER TIPS

Thanks to the reminder of David Wallace, I found this code in hashmap:

public V put(K key, V value) {
    if (key == null)
        return putForNullKey(value);
    int hash = hash(key.hashCode());
    int i = indexFor(hash, table.length);
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }

And it indeed invoke the hashCode() when put it into hashmap.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top