我一直在使用Java进行刽子手游戏。有人为我重新设计了这两种方法然后离开;这些方法必须有效,因为我的程序有效,我不知道他们做了什么。
你可以向我解释这段代码,好像你是为初学者评论它,并提供一个更简单的代码版本(可能更多if-then-elses),保持相同的功能吗?
问题,答案,信息在包含我遇到问题的两种方法的类中声明。
public class Question {
private final String question;
private final String answer;
private final String info;
}
并在此构造函数中初始化...
public Question(String question, String answer, String info) {
this.question = question;
this.answer = answer;
this.info = info;
}
问题1是在一个名为HangmanMain的不同类中声明和初始化的,就像这样...
private static List<Question> initQuestions() {
Question question1 = new Question("What is the statement terminating character in Java?", ";", "The semi-colon (;) is used to end a statement in Java.");
}
我遇到问题的两种方法:
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Question question1 = (Question) o;
if (answer != null ? !answer.equals(question1.answer) : question1.answer !=
null) return false;
if (info != null ? !info.equals(question1.info) : question1.info != null)
return false;
if (question != null ? !question.equals(question1.question) :
question1.question != null) return false;
return true;
}
public int hashCode() {
int result = question != null ? question.hashCode() : 0;
result = 31 * result + (answer != null ? answer.hashCode() : 0);
result = 31 * result + (info != null ? info.hashCode() : 0);
return result;
}
答案 0 :(得分:0)
equals()
方法过于复杂。你真的应该把它分成一个函数,用
private static boolean equals(String a, String b) {
if (a == null) {
return b == null;
}
return a.equals(b);
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Question)) {
return false;
}
Question that = (Question) o;
return (equals(this.answer, that.answer) && //
equals(this.info, that.info) && //
equals(this.question, that.question));
}
然后你可以从hashCode()
中删除三元组
public int hashCode() {
int result = 0;
if (question != null) {
result = question.hashCode();
}
if (answer != null) {
result = 31 * result + answer.hashCode();
} else {
result = 31 * result;
}
if (info != null) {
result = 31 * result + info.hashCode();
} else {
result = 31 * result;
}
return result;
}