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");

        System.out.println(a.hashCode());
        System.out.println(b.hashCode());
    }
}

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:

57651960
441366923

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.)

其他提示

It is the responsibility of the Student class to provide a proper equals() method which is consistent with the hashCode() contract. From the JavaDoc:

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.

And here the full example:

class Student {

    private int snr;
    private String name;

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

    @Override public boolean equals(Object obj) {
        if (!(obj instanceof Student)) return false;
        Student other = (Student) obj;
        return Objects.equals(snr, other.snr) && Objects.equals(name, other.name);
    }

    @Override public int hashCode() {
        return Objects.hash(snr, name);
    }
}

You have not overwritten the underlying Object.Hashcode, you would need something like this, your ide can generate hashcode and equals for you.

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

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

@override
public int hashcode(){
    int result = super.hashCode();
    result = 31 * result + (namn!= null ? namn.hashCode() : 0) + snr;
    return result;
  } 
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top