直到今天,我还相信具有相同哈希码的两个对象意味着它们都具有相同的内存位置。但下面的一段代码完全讲述了一个不同的故事:
学生实体:公共类学生实现 Comparable {
int id;
int marks;
String Subject;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getMarks() {
return marks;
}
public void setMarks(int marks) {
this.marks = marks;
}
public String getSubjects() {
return Subject;
}
public void setSubject(String subject) {
Subject = subject;
}
public Student() {
}
public Student(int id, String subject, int marks) {
super();
this.id = id;
this.marks = marks;
Subject = subject;
}
@Override
public int compareTo(Student o) {
if (this.getId()>(o.getId()))
return 1;
if (this.getId()<(o.getId()))
return -1;
return 1;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((Subject == null) ? 0 : Subject.hashCode());
result = prime * result + id;
result = prime * result + marks;
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 (Subject == null) {
if (other.Subject != null)
return false;
} else if (!Subject.equals(other.Subject))
return false;
if (id != other.id)
return false;
if (marks != other.marks)
return false;
return true;
}
}
长风秋雁
Helenr
温温酱
相关分类