3

This question's answer explains the situation with Java well. I would like to know what the situation is with Android. Specifically:

Question 1: For a given string, will the hash code always be the same? (Even more specifically, I need a hashcode of a given string to be the same on a user's phone each time the app is opened).

I googled for the source of android's String and found this, but I'm playing with fire because I don't know the first thing about Android source, if/when it's modified by manufacturers etc.

Question 2: If the answer to 1 is no, then would it be sensible for me to use the hashCode() code in the source quoted above in my own hashCode() function?

Community
  • 1
  • 1
Jodes
  • 14,118
  • 26
  • 97
  • 156

2 Answers2

6
  • The same String should has the same hashCode() (based on hashCode definition)

If you take a look at Android hashCode() of String class. You will see hashCode is calculated based on char array (the same), char count ( the same) and offset field ( this value seems always Zero (0) - is set in String constructor - I don't know why Google adds this offset field. Oracle String.hashCode() is calculated based on char array, char count only.

  • You can build your own hashCode() function like Oracle String hashCode(): This implementation is based on char array and char count so the same String always has the same hashCode().
LHA
  • 9,398
  • 8
  • 46
  • 85
4

As the hash-code algorithm is actually specified in the interface contract, and the Java-doc is also used as part of the Android SDK headers, I suppose you can count on it as being "stable".

But you might be better of to use a cryptographically strong hash function like SHA1 or SHA256 depending on your use-case, as they will also be a lot less likely to produce collisions (The Java hashCode() has only a 32-bit value range!).

Martin C.
  • 12,140
  • 7
  • 40
  • 52
  • Ah yes - but as it happens, if I want to override Object's `hashCode()` method, it can only return an int (32 bit) anyway! – Jodes Aug 14 '14 at 20:17