为什么hashCode的值是相同的,而所有都是不同的String对象

BON*_*TIF 0 java

为什么hashCode的值相同而所有是不同的String对象:

public class StringObj {

    public static void main(String[] args) {

        String s1="Jack";

        String s2=new String("Jack");

        String s3=new String("Jack");

        System.out.println(s1.hashCode());

        System.out.println(s2.hashCode());

        System.out.println(s3.hashCode());

  }

}
Run Code Online (Sandbox Code Playgroud)

Kon*_*kiy 5

Object 的Java 文档说如果另一个对象equals(),它必须具有相同的hashCode().这是有道理的,因为两个对象据说都代表着相同的东西.

从实际角度来看,这非常重要.它允许您使用众所周知的String来写入和读取地图,而不必使用单个对象键.