hashCode()
method is not for providing a unique identifier for an object. It rather digests the object's state (i.e. values of member fields) to a single integer. This value is mostly used by some hash based data structures like maps and sets to effectively store and retrieve objects.
If you need an identifier for your objects, I recommend you to add your own method instead of overriding hashCode
. For this purpose, you can create a base interface (or an abstract class) like below.
public interface IdentifiedObject<I> {
I getId();
}
Example usage:
public class User implements IdentifiedObject<Integer> {
private Integer studentId;
public User(Integer studentId) {
this.studentId = studentId;
}
@Override
public Integer getId() {
return studentId;
}
}