首页 > 解决方案 > 如何存储和检索数据

问题描述

如何使用 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 的答案!这个想法指向了工作结构。

标签: javagetter-setter

解决方案


您需要初始化categories. 默认情况下,它的值为null。这就是你例外的原因。


推荐阅读