我目前正在通过MOOC学习Java的哈希码,并遵循了他们的教程。但是,当哈希图中明显存在一个值时,预期输出将返回null。我的替代代码如下:
public class Plate{
private final String regCode;
private final String country;
// Counstructors
...
// accessors... only showing name for less clutter
getCode()
getCountry()
@Override // toString
public String toString(){
return country + " " + regCode;
}
@Override // equals
public boolean equals(Object obj){
if(obj == null){
return false;
}
if(getClass() != obj.getClass()){
return false;
}
Plate cmp = (Plate) obj;
if(this.country.equals(cmp.getCountry())){
return false;
}
if(this.regCode == null || this.regCode.equals(cmp.getCode())){
return false;
}
return true;
}
///////////////////////////////////// Below code may be the problem ///////////////////////////////////
@Override // hashCode
public int hashCode(){
if(this.country == null || this.regCode == null){
return 7;
}
return this.country.hashCode() + this.regCode.hashCode();
}
}
我使用上述代码的主要功能是:
import java.util.ArrayList;
import java.util.HashMap;
public class Regi{
public static void main(String[] args){
Plate reg1 = new Plate("FI", "ABC-123");
Plate reg2 = new Plate("FI", "UXE-465");
Plate reg3 = new Plate("D", "B WQ-431");
ArrayList<Plate> finnish = new ArrayList<Plate>();
finnish.add(reg1);
finnish.add(reg2);
Plate newPlate = new Plate("FI", "ABC-123");
if(!finnish.contains(newPlate)){
finnish.add(newPlate);
}
System.out.println("Finnish " + finnish);
// where unexpected result occur
HashMap<Plate, String> owners = new HashMap<Plate, String>();
owners.put(reg1, "Arto");
owners.put(reg3, "Jurgen");
System.out.println("Owners:");
System.out.println(owners.get(reg1));
System.out.println(owners.get(new Plate("FI", "ABC-123")));
System.out.println(owners.get(new Plate("D", "B WQ-431")));
}
}
预期输出是:
但是只要我运行null
和System.out.println(owners.get(new Plate("FI", "ABC-123")));
,我的输出就会在“所有者:”部分下方显示System.out.println(owners.get(new Plate("D", "B WQ-431")));
。我不确定我的自定义hashCode函数出了什么问题,因为我能够打印出country
和regCode
的两个hashCode,并且它们都给出了数值。我还引用了其他人的有关哈希码以使用质数的帖子,但该帖子仍显示为空。我想知道是否有人可以指出我关于hashCode的正确方向。
您的代码不起作用,因为当两个对象都具有same equals
时,使false
返回country
。或same regCode
:
if(this.country.equals(cmp.getCountry())){
return false;
}
if(this.regCode == null || this.regCode.equals(cmp.getCode())){
return false;
}
您缺少!
(NOT)运算符:
if (! this.country.equals(cmp.getCountry())) {
return false;
}
if (this.regCode == null || ! this.regCode.equals(cmp.getCode())) {
return false;
}
此外,您的hashCode()
实现意味着country
可以为null
,因此您缺少空检查:
if (this.country == null || ! this.country.equals(cmp.getCountry())) {
return false;
}