First post this code

At runtime, enter Java HashCode 123 123

public class HashCode {    public static void main(String[] args) {        String temp1 = new String(args[0]);        String temp2 = new String(args[1]);        System.out.println(temp1.hashCode());        System.out.println(temp2.hashCode());        Car car1 = new Car();        Car car2 = new Car();        Car car3 = new Car();                car1.name = "car1";        car1.id = "car11";        car2.name = "car2";        car2.id = "car22";        car3.name = "car1";        car3.id = "car11";        System.out.println(car1.hashCode());        System.out.println(car2.hashCode());        System.out.println(car3.hashCode());    }}
Copy the code

The results are as follows:

48690
48690
366712642
1829164700
2018699554
Copy the code

You can see that the two String variables from the input have the same result using the hashCode() method.

The first conclusion is that, without changing the original Java code, the return value of hashCode is always int.

Then there’s why a String with the same content yields different results than a Car with the same content.

Let’s first look at the implementation of the hashCode methods of the String, Integer, and other wrapper classes.

Public int hashCode() {int h = hash; if (h == 0 && value.length > 0) { char val[] = value; for (int i = 0; i < value.length; i++) { h = 31 * h + val[i]; } hash = h; } return h; } // Integer @Override public int hashCode() { return Integer.hashCode(value); } public static int hashCode(int value) { return value; }// Boolean @Override public int hashCode() { return Boolean.hashCode(value); } public static int hashCode(boolean value) { return value ? 1231-1237; }Copy the code

Just three implementations of hashCode have been shown above, and you can see the differences.

What does HashCode do?

First of all, if we have an array of 100 lengths, and we want to find one of the elements, the easiest way might be to go through the array and compare. First of all, if there is a large amount of data, the time will be longer.

Let’s borrow a HashMap from the web.

Why is it possible to find this element quickly using HashCode?

In fact, the resulting hashCode will somehow be computed into the array subscript of the HashMap, which saves a lot of time.

If you have two hashcodes that are the same then it proves that the two objects are stored in the same array element.

Because the above wrapper class’s HashCode methods are overridden.

Now let’s see how the Object hashCode method is implemented

    public native int hashCode();
Copy the code

?? I did this in C.

Then I couldn’t find it.

Unfinished…