Philip
Philip

Reputation: 38

Hashcode for string in different machine returns same value

I have read that hashcode in a JVM instance returns same value. But in another JVM instance, the same value may not be returned. I tried the following program:

public class demo {
  public static void main(String[] args) {
    String s = new String("Hello");
    System.out.println(s.hashCode());
 }
}

This program returns the same value as many number of times I rerun it on my machine. Also, I tried running the same program on other machines and everywhere I got the same value. Is it just coincidence?

I have a scenario where based on a strings value i'll determine the next business logic to follow. So currently I am doing

switch(s.hashcode()%4){
      case 0:....
      case 1:....
}

Should this work fine always?

Upvotes: 1

Views: 944

Answers (1)

nneonneo
nneonneo

Reputation: 179452

Whether the hashCode is the same across runs or not (whether it is deterministic) depends on the class. For example, String has a deterministic hashCode; Object does not. In general, you should not expect hashCode to be deterministic.

Furthermore, hashCode isn't random either. Object's hashCode, for example, is just the object's memory address, which might always be divisible by 4//

Upvotes: 2

Related Questions