It depends on what you mean:
As mentioned String.hashCode()
gives you a 32 bit hash code.
If you want (say) a 64-bit hashcode you can easily implement it yourself.
If you want a cryptographic hash of a String, the Java crypto libraries include implementations of MD5, SHA-1 and so on. You'll typically need to turn the String into a byte array, and then feed that to the hash generator / digest generator. For example, see @Bryan Kemp's answer.
If you want a guaranteed unique hash code, you are out of luck. Hashes and hash codes are non-unique.
A Java String of length N has 65536 ^ N
possible states, and requires an integer with 16 * N
bits to represent all possible values. If you write a hash function that produces integer with a smaller range (e.g. less than 16 * N
bits), you will eventually find cases where more than one String hashes to the same integer; i.e. the hash codes cannot be unique. This is called the Pigeonhole Principle, and there is a straight forward mathematical proof. (You can't fight math and win!)
But if "probably unique" with a very small chance of non-uniqueness is acceptable, then crypto hashes are a good answer. The math will tell you how big (i.e. how many bits) the hash has to be to achieve a given (low enough) probability of non-uniqueness.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…