【发布时间】:2019-11-02 06:08:56
【问题描述】:
我是 Java 新手(非常新)。 我试图了解 HashMap 和类的 equals 方法以及它如何覆盖重复项。 请看以下代码:
public class Student {
Integer StudentId;
String Name;
String City;
public Student(Integer studentId, String name, String city) {
super();
StudentId = studentId;
Name = name;
City = city;
}
public Integer getStudentId() {
return StudentId;
}
public String getName() {
return Name;
}
public String getCity() {
return City;
}
@Override
public int hashCode() {
System.out.println("haschode is called for " + this);
final int prime = 31;
int result = 1;
result = prime * result + ((StudentId == null) ? 0 : StudentId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
System.out.println("equals is called for " + this);
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (StudentId == null) {
if (other.StudentId != null)
return false;
} else if (!StudentId.equals(other.StudentId))
return false;
return true;
}
@Override
public String toString() {
return "\n Student [StudentId=" + StudentId + ", Name=" + Name + ", City=" + City + "] \n";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<Student, String> myMap = new HashMap<Student, String>();
myMap.put(new Student(1, "andy", "p"), "Great"); //Line 1
myMap.put(new Student(2, "sachin", "m"), "Better");
myMap.put(new Student(3, "dev", "s"), "Good");
myMap.put(new Student(1, "andy", "p"), "Excellent"); // Line 4
System.out.println(myMap);
}
}
现在,main() 中编写的代码仅在我编写代码以再次放置相同的键时调用 equals 方法,即“第 4 行”(请参阅我的代码缩进)。
为什么“第 2 行”和“第 3 行”没有调用 equals 方法?? 它应该为每个 put 行调用 equals .... 正确吗?
我在这里缺少一些理解,并留下了一些问题: (1) 为什么每个put都不调用equals方法来检查类成员的相等性? (2) 谁触发了Student类equals方法的调用?
【问题讨论】:
-
我在 main() 中没有看到像
equals()这样的代码 -
先生,第 4 行调用了 Student 类中编写的 equals() 方法。我不明白你的问题。