我有一节课: Question
它有id和content.
我有一个HashMap与Questions作为键和asnwers(Strings)作为价值.
我尝试使用for键从我的地图中查找答案Question.
但是它总是给出null值,我不知道为什么因为map确实包含了我的问题.
码:
Log.i("info", "map:");
Log.i("info", questionAnswers.toString());
Log.i("info", "================================");
Log.i("info", "question we are looking for:");
Log.i("info", question.toString());
Log.i("info", "================================");
Log.i("info", "anwer is null: " + questionAnswers.get(question));
Log.i("info", "================================");
Iterator it = questionAnswers.entrySet().iterator();
//Iterating the map just to get information for test's sake
while (it.hasNext()) {
Map.Entry<Question, String> entry = (Map.Entry<Question, String>) it.next();
//Question in the map
Question questionInCont = entry.getKey();
//Testing the equals method
if (questionInCont.equals(question)) {
Log.i("info", "================================");
Log.i("info", "question we are looking for is equals to a question in the map");
Log.i("info", questionInCont.getQuestionId() + " == " + question.getQuestionId());
String answer = questionAnswers.get(question);
//Great, equals working but still no answer back, only null
Log.i("info", "anwer is still null: " + answer);
Log.i("info", "================================");
}
}
Run Code Online (Sandbox Code Playgroud)
日志输出:
11-21 13:22:13.083: I/info(18350): map:
11-21 13:22:13.083: I/info(18350): {Question{questionId='9', content='What is your name?'}=John, Question{questionId='8', content='How old are you?'}=33}
11-21 13:22:13.083: I/info(18350): ================================
11-21 13:22:13.083: I/info(18350): question we are looking for:
11-21 13:22:13.084: I/info(18350): Question{questionId='8', content='How old are you?'}
11-21 13:22:13.084: I/info(18350): ================================
11-21 13:22:13.084: I/info(18350): anwer is null: null
11-21 13:22:13.084: I/info(18350): ================================
11-21 13:22:13.084: I/info(18350): ================================
11-21 13:22:13.084: I/info(18350): question we are looking for is equals to a question in the map
11-21 13:22:13.084: I/info(18350): 8 == 8
11-21 13:22:13.084: I/info(18350): anwer is still null: null
11-21 13:22:13.084: I/info(18350): ================================
Run Code Online (Sandbox Code Playgroud)
编辑:
感谢您的评论,我的问题类没有hashCode()功能.这是问题吗?
Question class:
public class Question implements Serializable {
String questionId;
String content;
public Question(String id, String content) {
this.questionId = id;
this.content = content;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Question) {
Question question = (Question) obj;
return questionId.equals(question.getQuestionId());
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
播下为什么我得到null作为答案?
您的主要问题是您只实现了该equals()方法.这对于HashMap的值是严格禁止的,因为equals()总是必须与它一起实现hashCode().
HashMap中的每个条目(m1)和第二个条目(m2)必须满足以下条件:m1.equals(m2)表示m1.hashCode()== m2.hashCode()