gpt4 book ai didi

java - object==object,不比较引用

转载 作者:行者123 更新时间:2023-11-30 07:46:05 25 4
gpt4 key购买 nike

我已经覆盖了哈希码和 equals 以找到具有相同 startDate 和 closingDate 的值。而且我得到了重复对象的类似哈希码。当等同于这些对象时,我得到 boolean 值“false”。在我的理解中,object==object 比较对象的引用,即使引用相同;代码返回 false。你能帮我理解问题是什么吗?我在下面发布了我的代码:

Hashcode & equals 方法

public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.startDate == null) ? 0 : this.startDate.getDate());
result = prime * result + ((this.closingDate == null) ? 0 : this.closingDate.getDate());
return result;
}

public boolean equals(Object customer) {
if(customer == null || customer.getClass()!= this.getClass())
return false;

return this==customer;
}

主.java

public class HashQuestion {
public static void main(String[]args) {
Map<Integer, Customer> custMap = new HashMap<Integer, Customer>();
custMap.put(1, createCustomer(1, new Date()));
custMap.put(2, createCustomer(2, new Date()));
custMap.put(3, createCustomer(3, new Date()));
Customer checkCustomer = createCustomer(1, new Date());
for (Customer cust : custMap.values()) {

if (cust.equals(checkCustomer)) {
System.out.println("Duplicate No: "+cust.getCustId()+ ", Start date: " +
cust.getStartDate().toString() + " End date: " +cust.getClosingDate().toString());
}
else
System.out.println("No: "+cust.getCustId()+ ", Start date: " +
cust.getStartDate().toString() + " End date: " +cust.getClosingDate().toString());
}
}

@SuppressWarnings("deprecation")
static Customer createCustomer(int number, Date date) {
Date closeDate = new Date();
Date startDate = new Date();
closeDate.setDate(date.getDate() + number);
startDate.setDate(date.getDate() - number);
return new Customer(number, number+1, startDate, closeDate);
}
}

输出:

No: 1, Start date: Wed Jun 20 19:42:46 IST 2018 End date: Fri Jun 22 19:42:46 IST 2018
No: 2, Start date: Tue Jun 19 19:42:46 IST 2018 End date: Sat Jun 23 19:42:46 IST 2018
No: 3, Start date: Mon Jun 18 19:42:46 IST 2018 End date: Sun Jun 24 19:42:46 IST 2018

检查客户对象引用:Customer@643

对象引用(在 map 中):[Customer@643, Customer@625, Customer@607]

此处 object1 与 checkCustomer obj 具有相同的引用。但是 obj==checkCustomer,返回 false。

最佳答案

由此改变:

Map<Integer, Customer> custMap = new HashMap<Integer, Customer>();
custMap.put(1, createCustomer(1, new Date()));
custMap.put(2, createCustomer(2, new Date()));
custMap.put(3, createCustomer(3, new Date()));
Customer checkCustomer = createCustomer(1, new Date()); //This is a different reference

对此:

Map<Integer, Customer> custMap = new HashMap<Integer, Customer>();
Customer checkCustomer = createCustomer(1, new Date());
custMap.put(1, checkCustomer); //Now this is the same reference
custMap.put(2, createCustomer(2, new Date()));
custMap.put(3, createCustomer(3, new Date()));

您正在创建 4 个不同的客户,这将创建三个。

关于java - object==object,不比较引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50970865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com