You are computing the hash on a compile time constant value, so that
value is itself a compile tiem constant, and can be deived from the
memory location where that constant gets allocated when the JVM starts
up. This works for strings as they are all internalized at compile time,
that is stored in a common table that holds a unique copy of each
String, that way the storage location corresponds with the content of
the String, and so does the hash value.
If you look at the code for String.java, you will see it actually
computes the hash value based on the characters it contains. This only
is used on strings you create while your code is running.
--
Eduard
Shaun Flynn wrote on 06/05/2021 17:22:
I ran into this, thinking it would be the same per execution, but it
does not work like that.
If you create a for loop doing something like...
String test = "Hello World!";
for(i = 0; i < 100; i++) {
System.out.println(test.hashCode());
}
You will get 100 identical values.
Run it again, you will get 100 values identical values again, but the
value has changed.
Ie first run prints "46521890" 100 times
Second run prints "-56905325700" 100 times
And each subsequent run with produce a different hashCode repeated 100
times.
I believe (feel free to correct me) that the algorithm or formula for
producing ths hashCode has the memory address as an input, thus it
will different per execution because the JVM allocates the memory,
which has the effect of appearing random.
It confused me at first, but this is the intended functionality: if
you are intending to store hashes for lookup or other purposes, use
one of the already defined hash functions eg
https://www.geeksforgeeks.org/sha-256-hash-in-java/
Hope this helps.
Shaun
On Thu, 6 May 2021, 13:46 Charles Johnson, <cehjohn...@gmail.com
<mailto:cehjohn...@gmail.com>> wrote:
On 06/05/2021 12:37, Christopher C. Lanz wrote:
It would be helpful if I could rely on hashCode*always* to return
the same integer for the same object.
What are you doing such that needs to be the case?
CJ