我有一个hashmap,其中key是我的内部类“Key”的对象。
我的问题是,当我使用get(key)时,它永远不会回馈任何东西。因为get with equals我在我的Key类中覆盖了equals,所以它应该适用于get方法,但显然它不适用。
有什么建议吗?
CODE:
public class Infrastruktur
{
private Zuechter online;
private HashMap<Key,Zuechter> zuechter;
Infrastruktur()
{
zuechter = new HashMap<Key,Zuechter>();
}
}
public void login(String name, String passwort)
{
Key hashMapKey = new Key(name, passwort);
if(this.zuechter.get(hashMapKey) != null)
this.online = this.zuechter.get(hashMapKey);
}
public void register(String name, String passwort)
{
if(name != null && passwort != null)
{
this.zuechter.put(new Key(name,passwort),new Zuechter());
login(name, passwort);
}
}
public void logOut()
{
this.online = null;
}
public Zuechter getOnline() {
return this.online;
}
private class Key
{
String name;
String passwort;
Key(String name, String passwort)
{
this.name = name;
this.passwort = passwort;
}
@Override
public boolean equals(Object o)
{
if (o == null) return false;
if (o == this) return true;
if (!(o instanceof Key)) return false;
Key key = (Key)o;
if(this.name.equals(key.name) && this.passwort.equals(key.passwort)) return true;
return false;
}
}
/* Testing */
public static void main(String[] args)
{
Infrastruktur inf = new Infrastruktur();
inf.register("Jakob", "passwort");
inf.logOut();
inf.login("Jakob", "passwort");
System.out.println(inf.getOnline().test());
}
}
如果我运行该类,这是我得到的输出:
not found
not found
Exception in thread "main" java.lang.NullPointerException
at Infrastruktur.main(Infrastruktur.java:105)
答案 0 :(得分:2)
您还应该为hashCode()
课程实施Key
。示例实现可以是:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + name.hashCode();
result = prime * result + passwort.hashCode();
return result;
}
答案 1 :(得分:2)
使用Eclipse生成类的hashCode
方法。在任何Map
方案中,Java哈希键值以允许0(1)读访问。
如果找到,它只是哈希跳转到引用。所有Java IDE都有Generate hashCode and equals
选项。一个简单的例子,省略了null
检查。
@Override
public int hashCode() {
int hash = 3;
hash = 7 * hash + this.name.hashCode();
hash = 7 * hash + this.passwort.hashCode();
return hash;
}
答案 2 :(得分:1)
您必须覆盖覆盖equals()的每个类中的hashCode()。如果不这样做,将导致违反Object.hashCode()的常规合同,这将阻止您的类与所有基于散列的集合(包括HashMap,HashSet和Hashtable)一起正常运行。
来自Effective Java的,来自Joshua Bloch
tl; dr要么手动生成hashCode(),
@Override
public int hashCode() {
int hash = 31;
hash = 29 * hash + Objects.hashCode(name);
hash = 29 * hash + Objects.hashCode(passwort);
return hash;
}
使用IDE hashCode生成,或者只使用泛型(尽管速度较慢)
@Override
public int hashCode() {
return Objects.hash( name, passwort );
}
...你甚至可以使用反射为任何类编写一个通用的hashCode()(非常慢,但作为占位符很好)
顺便说一句,在hashCode()中省略null检查可变或不可变对象,将null作为有效字段值是将错误引入代码的最简单方法之一 - 这正是为什么需要显式检查或Objects.hashCode()的原因