我想创建一个可以由“客户编号”唯一标识的“客户”类。
我写了下面的代码
public class Customer{
private Integer customerNo;
private String customerName;
public Customer(Integer customerNo, String customerName){
this.customerNo = customerNo;
this.customerName = customerName;
}
@Override
public int hashCode(){
return this.customerNo;
}
public Integer getCustomerNo(){
return this.customerNo;
}
public String getCustomerName(){
return this.customerName;
}
@Override
public boolean equals(Object o){
Customer cus = (Customer) o;
return (this.customerNo == cus.getCustomerNo() && this.customerName != null && this.customerName.equals(cus.getCustomerName()));
}
@Override
public String toString(){
StringBuffer strb = new StringBuffer();
strb.append("Customer No ")
.append(this.customerNo)
.append(", Customer Name ")
.append(this.customerName)
.append("\n");
return strb.toString();
}
public static void main(String [] args){
Set<Customer> set = null;
try{
set = new HashSet<Customer>();
set.add(new Customer(1,"Jack"));
set.add(new Customer(3,"Will"));
set.add(new Customer(1,"Tom"));
set.add(new Customer(3,"Fill"));
System.out.println("Size "+set.size());
}catch(Exception e){
e.printStackTrace();
}
}
}
从上面的代码中,您可以看到我将哈希码作为客户编号返回。
我的平等也基于客户编号和客户名称
如果我运行上面的代码,输出将是
D:\Java_Projects>java Customer
Size 4
D:\Java_Projects>
输出是由相同客户编号创建的4个对象。原因是即使客户编号为0。相同,但名称不同,根据我上面基于“客户编号”和“客户名称”的“等于”实现方式。作为CustomerNo-CustomerName的4种不同组合,因此创建了4个对象。
我的问题是
我上面的哈希码实现是不好的做法吗?
我会遇到什么失败?
如果我与同一个客户一起创建500,000个Customer对象,该怎么办?
是否将500,000个客户对象放在同一个存储桶中?
我上面的哈希码实现是不好的做法吗?
假设不同的客户在customerNo
大多数时间都有不同的情况,这是一个很好的实现。在现实世界的应用程序中,customerNo
最有可能是唯一标识符,唯一性由数据库约束保证。
我会遇到什么失败?
你还没有处理,其中的情况customerNo
是null
。这是一种方法:
public int hashCode(){
return Objects.hash(customerNo);
}
当这将返回0 customerNo
是null
。
该equals
方法还有另一个错误:Integer
不应将对象与进行比较==
,这会给您带来意想不到的结果。此外,customerName
设置为的两个客户null
永远都不相等。该Objects.equals
方法解决了这些问题。
return Objects.equals(this.customerNo, cus.customerNo)
&& Objects.equals(this.customerName, cus.customerName);
如果我与同一个客户一起创建500,000个Customer对象,该怎么办?是否将500,000个客户对象放在同一个存储桶中?
在这种情况下,所有对象实际上都将放置在同一存储桶中。您HashSet
将其简化为链表数据结构,并且性能会很差:要找到客户对象,数据结构必须在最坏的情况下将给定对象与每个对象进行比较。
如果Customer
实现Comparable
,则哈希表存储桶可以使用二进制搜索树而不是链接列表,并且性能不会受到严重影响。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句