Since String
in Java (like other languages) consumes a lot of memory because each character consumes two bytes, Java 8 has introduced a new feature called
Since your first question has already been answered, I'll answer your second question.
The String
objects must be compared character by character, because though equal Object
s implies equal hashes, the inverse is not necessarily true.
As Holger said in his comment, this represents a hash collision.
The applicable specifications for the hashcode()
method are as follows:
If two objects are equal according to the
equals(Object)
method, then calling thehashCode
method on each of the two objects must produce the same integer result.It is not required that if two objects are unequal according to the
equals(java.lang.Object)
method, then calling thehashCode
method on each of the two objects must produce distinct integer results. ...
This means that in order for them to guarantee equality, the comparison of each character is necessary in order for them to confirm the equality of the two objects. They start by comparing hashCode
s rather than using equals
since they are using a hash table for the references, and this improves performance.