java - 如何存储和检索数据
问题描述
如何使用 getter 和 setter?半问题:如何创建结构以轻松检索数据?
在 setter 中设置数据后,我无法从 getter 中检索它。
结构如下:
Interaction - parent class with getters and setters
Dictionary, CategoryInteraction, WordsInteraction - subclasses
这是我的代码:
public class Dictionary extends Interaction {
private String resource = "/home/kjlk/IdeaProjects/Jdf/src/fdf/res";
private File resourceFile = new File(resource);
private Scanner scanner;
private LinkedHashMap<Integer, String> categories;
public void getCategoriesFromDictionary() {
Interaction interaction = new Interaction();
try {
scanner = new Scanner(resourceFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
categories = new LinkedHashMap<>();
int categoriesCount = 1;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.startsWith("_")) {
categories.put(categoriesCount, line);
categoriesCount++;
}
}
scanner.close();
setCategories(categories);
}
}
public class Interaction {
private LinkedHashMap<Integer, String> categories;
public LinkedHashMap<Integer, String> getCategories() {
return categories;
}
public void setCategories(LinkedHashMap<Integer, String> categories) {
this.categories = categories;
}
}
public class CategoryInteraction extends Interaction {
public void printCategories() {
LinkedHashMap<Integer, String> categories = getCategories();
for (Integer key : categories.keySet()) {
System.out.println(key + ": " + categories.get(key));
}
System.out.println();
}
}
我收到 NullPointerException :
LinkedHashMap<Integer, String> categories = getCategories();
先感谢您!请不要向我推荐 NPE 的答案!这个想法指向了工作结构。
解决方案
您需要初始化categories
. 默认情况下,它的值为null。这就是你例外的原因。
推荐阅读
- r - case_when() 在管道中发生变异但保留原始数据
- r - 等级 ”?” 或在 R 中为空
- promise - qbo3 Javascript 承诺
- r - ggplot2甜甜圈图图例问题与“a”
- c++ - ASan:在递归函数中 vector.emplace(push)_back 之后的堆使用后释放
- ios - 如何在没有 Cocoapods 的情况下在我的颤振应用程序中获取 webview_flutter 插件
- python - 如何将值转换为列并将其他列中的值放入熊猫中的这些列中
- angularjs - 在 Rxjs 的 map 运算符中,大括号内的 body 和圆括号内的 body 代表什么?
- python - 如何停止遍历枚举列表的循环?
- python - 如何在下面的代码中打印字典中的值?