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?

2 Answers 2

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().
Sign up to request clarification or add additional context in comments.

Comments

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!).

1 Comment

Ah yes - but as it happens, if I want to override Object's hashCode() method, it can only return an int (32 bit) anyway!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.