I
I
Ilya Podolsky2021-10-27 14:14:02
Java
Ilya Podolsky, 2021-10-27 14:14:02

Why do strings always have the same hashcode()?

String str1 = "Hello";
String str2 = "Hello";

Two String objects with different references.

Same as for example:
Ob ob1 = new Ob("Object", 1);
Ob ob2 = new Ob("Object", 1);


The same two objects with different references, but they will have different hashcode() than String

Question: why?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
O
Orkhan, 2021-10-27
@lamerizhottabicha

Good afternoon.
Here is the answer to your question:
https://www.baeldung.com/java-string-immutable
Why_String_Is_Immutable_In_Java.jpg

M
Mercury13, 2021-10-27
@Mercury13

String str1 = "Hello";
String str2 = "Hello";

Here is the same link. But even if you make them different objects, everything will be the same.
Let's start with what a hash code is. If the objects are equal, their hash codes are guaranteed to be equal. If they are not equal, then the hash codes, most likely (but not necessarily!) Are not equal. And now - about what "equal objects" are.
Initially, the equality of objects is checked simply: no two objects are equal, the object is equal to itself and no one else. In such a case, it's natural to somehow build a hash code from the address. For strings, this is not the case, and the hashCode() function is rewritten to take into account the data inside, and not the address.
(Why I say “somehow” - with a certain hash table structure, if you take just an address, some of the sockets will be idle. So the structure of the hash function and the hash table must be coordinated so that the table is filled evenly.)

V
Vasily Bannikov, 2021-10-27
@vabka

Because:
1. In fact, they have the same references, because during compilation all string literals turn into constants.
2. This is necessary so that you can normally use strings as keys in the map.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question