Why Object.hashCode () does not return the same value for seemingly identical objects


The code is as following:

public class Main {
    public static void main(String[] args) {
        Student a = new Student(10, "Ole");
        Student b = new Student(10, "Ole");


and the object looks like this:

public class Student {
    private int snr;
    private String namn;

    public Student(int snr, String namn) {
        this.snr = snr;
        this.namn = namn;

These are the results when running the code:


I've read some of the javadoc, but I can't find out why, can anyone explain why this happens? And also what I would have to do to make the result identical? (if at all possible)

Thanks for the explanations :)! Makes sense now ;)

You are not overriding Object.hashCode(), so it's returning a value based on the object identity.

From the documentation:

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)