I have found similar questions, but none of them have really helped me so far (which probably means I am doing something wrong, which is why I'm here).
I have a HashMap Map<Integer, List<Book>> that is supposed to have a Student's ID as the key and the list of Book he has in his possession as the value. Although only passing the ID as the key works, I feel like it isn't an object-oriented enough approach and that I should use Student as the key (so it'd look like so: Map<Student, List<Book>>). I tried to use it, but then I got a bunch of errors when I tried to return a given Student's list of Book, most likely because the Student wasn't found. My professor suggested me to @Override Java's hashCode and equals methods, which makes sense, since that's how HashMap compares keys, but I haven't had success in that (I am not sure what exactly I need to compare in order to see if two Student are the same; supposedly, their ID alone should work). Here are the overridden methods:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (id != other.id)
return false;
return true;
}
What am I doing wrong? Any light you could shed on this would be extremely helpful. Thanks in advance!
if (id != other.id) return false; return true;Why did you prefer this toreturn id.equals(other.id);?