String Deduplication feature of Java 8

后端 未结 4 1858
难免孤独
难免孤独 2020-11-28 02:06

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

4条回答
  •  感情败类
    2020-11-28 03:02

    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 Objects 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 the hashCode 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 the hashCode 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 hashCodes rather than using equals since they are using a hash table for the references, and this improves performance.

提交回复
热议问题