我创建Person
如下:
public class Person {
private String sCode;
private String sDate;
Person(String sCode, String sDate) {
this.sCode = sCode;
this.sDate = sDate;
}// Constructor and other methods...
@Override
boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person oPerson = (Person) obj;
return oPerson.sCode == this.sCode && oPerson.sDate == this.sDate;
}
@Override
public int hashCode() {
return Objects.hash(this.sCode, this.sDate);
}
}
我想将Person
对象存储在HashSet
(personSet)中:
HashSet<Person> personSet = new HashSet<>();
Person person1 = new Person("Aman", "2021-01-01");
Person person2 = new Person("Aman", "2021-01-01");
personSet.add(person1);
personSet.add(person2);
System.out.println(personSet.size()); //Expected size to be "1"
但是我收到Caught: java.lang.StackOverflowError
以下错误:
Caught: java.lang.StackOverflowError
java.lang.StackOverflowError
at Person.equals(Person.groovy:12)
有人可以告诉我为什么我的代码会抛出这个错误吗?