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> 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
>

Reply via email to