equals()方法和hashcode()理解问题
这是科夫曼一本书的练习练习。数据结构:使用Java的抽象和设计,第三版。
我有一系列问题。我已经尝试了2次尝试。第21-29行对我而言是逻辑上有意义的,而无需检查参考,而32-41则是根据本书改编的。
行20-30是否正确实现了equals()替代方法?我可以有2个字符串参数,并检查这些参数是否与“人对象” 2个字符串参数匹配?
行33-41我不知道发生了什么或是否正确。我从书中偷走了代码,但在这里更改了2个字符串参数的实现?
2 a)这些线以?
开始是否正确2 b)在第34行上的实例在这里检查什么?只是那个人 对象也是吗?或更多?
2 b 1)如果有更多到2a,还在检查什么?
3)第45和46行,这种方法实际在做什么?
1 public class Person {
2
3 String lastName;
4 String firstName;
5
6
7 public Person(String lastName, String firstName) {
8 this.lastName = lastName;
9 this.firstName = firstName;
10 }
11
12 public String toString() {
13
14 String result = ("First name: " + firstName +
15 "\nLast name: " + lastName);
16
17 return result;
18 }
19
20 public boolean equals(String lastName, String firstName) {
21
22 if (this.lastName == lastName && this.firstName == firstName) {
23
24
25 return true;
26 }
27
28 return false;
29
30 }
31
32
33 public boolean equals(Object obj) {
34 if (obj instanceof Person) {
35 return firstName.equals(((Person) obj).firstName)
36 && lastName.equals(((Person) obj).lastName);
37
38 }
39
40 return false;
41 }
42
43
44
45 public int hashcode() {
46 return lastName.hashCode() + firstName.hashCode();
47 }
48
49
50
51
52 }
This is a practice exercise from a book by Koffman. Data Structures: Abstraction and Design Using Java, 3rd Edition.
I have a series of questions. I have had 2 attempts at the equals method. Lines 21-29 are what made sense to me logically without checking references, and 32-41 are adapted from the book.
Are lines 20-30 a correct implementation of an equals() override method? Can I have 2 String parameters and check if these parameters match with the Person Objects 2 String parameters?
Lines 33-41 I have no idea what is occurring or if it's correct. I stole the code from the book but changed implementation here for 2 String parameters?
2 a) Are these lines correct to start with?
2 b) What does instanceof on line 34 check for exactly here? Just that Person is an
Object too? Or more?2 b 1) If there's more to 2a, what else is being checked?
3 ) Line 45 and 46, What is this method actually doing?
1 public class Person {
2
3 String lastName;
4 String firstName;
5
6
7 public Person(String lastName, String firstName) {
8 this.lastName = lastName;
9 this.firstName = firstName;
10 }
11
12 public String toString() {
13
14 String result = ("First name: " + firstName +
15 "\nLast name: " + lastName);
16
17 return result;
18 }
19
20 public boolean equals(String lastName, String firstName) {
21
22 if (this.lastName == lastName && this.firstName == firstName) {
23
24
25 return true;
26 }
27
28 return false;
29
30 }
31
32
33 public boolean equals(Object obj) {
34 if (obj instanceof Person) {
35 return firstName.equals(((Person) obj).firstName)
36 && lastName.equals(((Person) obj).lastName);
37
38 }
39
40 return false;
41 }
42
43
44
45 public int hashcode() {
46 return lastName.hashCode() + firstName.hashCode();
47 }
48
49
50
51
52 }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不。
与参考标识
this.lastName
的参考与参考标识代码> lastname 。您不想要这一点 - 您可以拥有2个相同的字符串,这些字符串与实际对象不同。您想要的是this.lastname.equals(lastName)
,尽管它需要努力。 (因此,真的,if(this.lastName == null)返回lastName == null; return this.lastname.equals(lastName);
)。这不是等于方法。 Equals方法具有签名
布尔值等于(对象其他){}
。第33行是正确的签名。不是nullsafe。平等方法不应该抛出任何东西。请参阅上面的解决方法。
再次在这里是一个问题,否则,嗯,很好。您可以做得更好,但这只是一种优化。这是略带理想的原因是深奥的。 (它给出了相同的哈希码,例如“彼得·杰克逊”和“杰克逊·彼得”,这是略有优化的)。
我没有你的教科书,你没有提到。因此,堆栈上没有人可以回答这个问题。一个等值方法必须看起来像
public boolean equals(object ottre)
。时期。我可以问你这本书是否等于那只狗。答案很明显:呃,不。
这里也发生了同样的事情。
对象
是许多事物的超级型。我可能会这样做:在这种情况下,我们必须查看名称才能弄清楚。 (<代码>其他人检查将成功)。
但是我也可以做:
在这种情况下狗)。等价方法应返回
false
,它不应引发异常。那你就读了。那就是..不正确,根本没有任何意义。这将在任何对象上调用
hashcode()
lastName 字段指向。无需知道它是如何工作的。它不会返回内存地址。如果这样做,这将被打破(作为2个对象的hashCode,其值是相同的,但它们不在同一内存地址,必须返回相同的哈希码,这就是hashcode:hashCode:相等的对象必须具有相等的哈希码(但相等的哈斯码在一般而言,不应当 )。 “生成” optino),或者让诸如Lombok或Autovalue项目之类的工具执行此操作。
No.
This compares the reference identity of
this.lastName
with the reference identity of parameterlastName
. You don't want that - you can have 2 identical strings that aren't the same actual object. What you want isthis.lastName.equals(lastName)
, though it needs null-guarding. (So, really,if (this.lastName == null) return lastName == null; return this.lastName.equals(lastName);
).This isn't an equals method. The equals method has signature
boolean equals(Object other) {}
. Line 33's is the right signature.Isn't nullsafe. equals methods are not supposed to throw anything. See above on how to fix that.
Again the null thing is a problem here, otherwise, eh, it's fine. You could do better, but that'd just be an optimization. The reason this is slightly suboptimal is esoteric. (It gives the same hashcode for e.g. "Peter Jackson" and "Jackson Peter", which is slightly suboptimal).
I don't have your textbook, you didn't mention it. Nobody on Stack Overflow can answer this question as a consequence. An equals method must look like
public boolean equals(Object other)
. Period.I can ask you if this book is equal to that dog. The answer is a rather obvious: Uh, no.
The same thing is happening here.
Object
is the supertype of many things. I might be doing this:In which case we'd have to look at names to figure it out. (the
other instanceof Person
check would succeed).But I could also do:
In which case the instanceof check will fail, and we want it to, because if you try to cast the parameter to
Person
, it would fail - it isn't (it's a dog). The equals method should returnfalse
, it should not throw an exception.You've read a lie then. That's.. just incorrect and makes no sense at all. This invokes the
hashCode()
method on whatever object thelastName
field is pointing at. There's no need to know how it works. It does not return memory addresses. If it did, this would be broken (as the hashCode of 2 objects whose value are identical, but which do not live at the same memory address, must return the same hashcode, that's the point of hashcode: Equal objects must have equal hashcode (but equal hashcode does not neccessarily mean equal objects).In general you should not be writing your own equals and hashCode implementations. Let java do it (records), your IDE do it (the source menu has a 'generate' optino), or let tools like Project Lombok or AutoValue do it.
将Java对象视为一个人,其
HashCode()
是他/她居住的房屋的地址。多人可以住在同一房子里(共享相同的hashcode )因此,一旦到达正确的房屋,您将需要一种其他机制来找到所需的实际人。那就是
quare()
发挥作用的地方。当且仅当等于()
告诉您时,该房屋中的两个人被视为“不同”。默认情况下,Java的
等于()
比较了两个对象的引用。但是,您可以覆盖等于()
,以实现您自己的标准何时应将两个人视为同一个人。两个人可以具有完全不同的身份,但是只要您的标准 说他们是qualie()
,那么他们就被视为同一个人。因此,考虑到这一点
不,因为您要比较两个人,而不是两个字符串
,您在屋子里选择一个随机的人,想检查这个人是否与另一个对象是同一个人,但是另一个对象实际上可以是任何东西(电视,冰箱,Trashbin等)。作为第一步,您想验证另一个对象确实是一个人(第34行)。如果是这种情况,请调用您的
等于
标准以判断两者是否应视为同一个人(第35和36行)。它返回对象和其他对象也居住的内存“存储桶”的地址。也就是说,它返回共享房屋的地址。
Think of a Java object as a person and its
hashcode()
as the address of the house he/she lives in. Multiple persons can live in the same house (sharing the samehashcode
) so once you arrive at the correct house, you will need an additional mechanism to find the actual person you are looking for. That's whereequal()
comes into play. Two people in that house are seen as "different" if and only ifequal()
tells you so.By default, Java's
equal()
compares the references of the two objects. However, you can overrideequal()
to implement your own criteria of when two people should be treated as the same person. Two people can have completely different identities, but as long as your criteria say that they'reequal()
, then they are treated as one and the same person.So, with that in mind
No, since you are comparing two persons, not two string
Says, you choose a random person in the house and want to check if this person is the same person as another object, but the other object can literally be anything (TV, fridge, trashbin, etc.). As the first step you want to verify that the other object is indeed a person (line 34). If that is the case, then invoke your
equal
criteria to judge if the two should be treated as the same person (line 35 and 36).It returns the address of the "bucket" of memory that the object and possibly other objects also live in. That is, it returns the address of the share house.