我正在开发一个 Android 应用程序来帮助 child 子学习数学。它将显示一些问题,用户可以回答这些问题。在起始页上会有一些选项可供选择。例如,位数和操作类型(即+、-、*、+/-)以及定时器是否启用。所以我创建了一个 QuestionOptions
类。
public class QuestionOptions implements Parcelable{
protected QuestionOptions(Parcel in) {
digitCount = in.readInt ();
}
public static final Creator<QuestionOptions> CREATOR = new Creator<QuestionOptions> () {
@Override
public QuestionOptions createFromParcel(Parcel in) {
return new QuestionOptions (in);
}
@Override
public QuestionOptions[] newArray(int size) {
return new QuestionOptions[size];
}
};
public QuestionOptions (OperationType operationType, int digitCount, boolean timerEnabled) {
this.operationType = operationType;
this.digitCount = digitCount;
this.timerEnabled = timerEnabled;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable (this, flags);
}
public enum OperationType {
ADDITION,
SUBTRACTION,
ADD_AND_SUB,
MULTIPLICATION
}
public boolean isTimerEnabled() {
return timerEnabled;
}
public void setTimerEnabled(boolean timerEnabled) {
this.timerEnabled = timerEnabled;
}
public OperationType getOperationType() {
return operationType;
}
public void setOperationType(OperationType operationType) {
this.operationType = operationType;
}
public int getDigitCount() {
return digitCount;
}
public void setDigitCount(int digitCount) {
this.digitCount = digitCount;
}
private OperationType operationType;
private int digitCount;
private boolean timerEnabled;
}
请注意,我实现了 Parcelable,因为我想将其发送到另一个 Activity 。 到目前为止,一切都很好。但后来我想添加一个功能来给用户提供奖品。现在我在网上找到了一些照片作为奖杯之类的东西。我希望它们的工作方式如下:对于每个可能的问题选项,都有不同的奖励。经过一番计算,我发现有22个可能的问题选项!所以我决定用一个hashmap来存储可能的问题选项(key)和奖杯图片的资源id(value)。
因为这是我第一次使用 HashMap ,所以我用它做了一些实验,很快发现我不能使用它。
HashMap.get
方法比较问题选项的引用,而不是其中的字段。这是我的测试:
HashMap<QuestionOptions, Integer> map = new HashMap<> ();
map.put(new QuestionOptions (QuestionOptions.OperationType.ADDITION,
1, false), 0);
map.put(new QuestionOptions (QuestionOptions.OperationType.ADDITION,
2, false), 1);
map.put(new QuestionOptions (QuestionOptions.OperationType.ADDITION,
3, false), 2);
System.out.println (map.get(
new QuestionOptions(QuestionOptions.OperationType.ADDITION,
1, false)));
它打印“null”...
读完这么多,你们一定睡着了……我只是想问:
如何将所有可能的问题选项放入 HashMap 中并使用新实例将它们取出,或者是否有其他方法来实现要求?如果是,如何?
最佳答案
您需要实现 QuestionOptions 的 hashcode() 和 equals() 方法。正如你所说
The HashMap.get method compares the references.
这是 hashCode() 的默认实现HashMap 用于比较键的方法
您可以阅读有关 hashCode and equals method here 的更多信息
关于java - 如何将内容放入 HashMap 并使用具有相同字段值的新实例来获取相应的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32174482/