Java 从哈希表获取值返回null
我在哈希表中保存了一个字符串值, 但是当我试图得到它时,我总是得到空值 有人知道为什么吗 这是操作侦听器的代码:Java 从哈希表获取值返回null,java,hashtable,actionlistener,Java,Hashtable,Actionlistener,我在哈希表中保存了一个字符串值, 但是当我试图得到它时,我总是得到空值 有人知道为什么吗 这是操作侦听器的代码: private class ButtonListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { if (e.getSource()==btnSave){ int day = Integer.parse
private class ButtonListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource()==btnSave){
int day = Integer.parseInt((String)daysBox.getSelectedItem());
int month = Integer.parseInt((String)monthsBox.getSelectedItem());
int year = Integer.parseInt((String)yearsBox.getSelectedItem());
MyDate date = new MyDate(day, month, year);
System.out.println(date);
diary.put(date,textArea.getText());
textArea.setText(null);
}
if (e.getSource()==btnShow){
int day = Integer.parseInt((String)daysBox.getSelectedItem());
int month = Integer.parseInt((String)monthsBox.getSelectedItem());
int year = Integer.parseInt((String)yearsBox.getSelectedItem());
MyDate date = new MyDate(day, month, year);
String s = diary.get(date);
textArea.setText(s+" ");
}
很可能,您没有覆盖
MyDate
类的hashCode
和equals
方法。哈希表依赖于这些方法来确定两个对象何时被视为相等。如果您没有覆盖它们,哈希表将比较MyDate对象,以查看它们是否是相同的实例,它们永远不会出现在您的代码中,因为它们是每次执行get/put调用时创建的new
实例
在MyDate类中,您需要以下内容:
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof MyDate)) return false;
MyDate d = (MyDate)o;
return this.day == d.day && this.month == d.month && this.year == d.year;
}
@Override
public int hashCode() {
return ((day * 31) + month) * 31 + year; // 31=prime number
}
很可能,您没有覆盖
MyDate
类的hashCode
和equals
方法。哈希表依赖于这些方法来确定两个对象何时被视为相等。如果您没有覆盖它们,哈希表将比较MyDate对象,以查看它们是否是相同的实例,它们永远不会出现在您的代码中,因为它们是每次执行get/put调用时创建的new
实例
在MyDate类中,您需要以下内容:
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof MyDate)) return false;
MyDate d = (MyDate)o;
return this.day == d.day && this.month == d.month && this.year == d.year;
}
@Override
public int hashCode() {
return ((day * 31) + month) * 31 + year; // 31=prime number
}
@博恩给了你最好的答案。当出现这样的问题时,最好的方法是在
String s=diary.get(date)上设置断点编码>并进入函数。您可能已经看到了为什么它没有找到您的MyDate对象。@Boann给了您最好的答案。当出现这样的问题时,最好的方法是在String s=diary.get(date)上设置断点编码>并进入函数。您可能已经了解了为什么它找不到MyDate对象。