当从另一个类访问时,公共静态HashMap实例返回NULL,即使我在构造函数中填充值

时间:2016-07-09 17:51:09

标签: java hashmap

我正在尝试创建一个字典来学习Java,它将读取wordlist.txt中预定义的单词

subterfuge:something intended to misrepresent the true nature of an activity
stymie:thwarting and distressing situation;

但是当我尝试访问声明为ReadToHashmap的{​​{1}}类的地图实例时,它允许我访问但是它始终返回public static

如何根据null更新所有HashMap来访问地图实例?

wordlist.txt

另一个班级

public class ReadToHashmap {
    public static   Map<String, String> map = new HashMap<String, String>();

    public ReadToHashmap() {
        // TODO Auto-generated constructor stub
    }

    public static Map getHasMap()
    {
        return map;
    }

    public static void main(String[] args) throws Exception {


        try{
            BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\Maxs\\workspace\\Dictionary\\src\\wordlist.txt"));
            String line = "";
            while ((line = in.readLine()) != null) {
                String parts[] = line.split(":");
                map.put(parts[0], parts[1]);
            }       
            in.close(); 
        }
        catch(Exception e)
        {
            System.out.println("Erro " +e.getMessage());
        }      



        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry)it.next();
            System.out.println(pair.getKey() + " = " + pair.getValue());
            it.remove(); // avoids a ConcurrentModificationException
        }

        findMeaning word = new findMeaning();
        String inputWord;
        String outputWord;
        System.out.println("Enter rge word to be searched  " );
        inputWord = word.getTheWord();
        outputWord =word.getFromDictionary(inputWord);
        System.out.println("Thge meaning is  " +outputWord);
    }
}

2 个答案:

答案 0 :(得分:3)

您的main方法填充地图,然后遍历其所有条目并删除它们中的每一个。很明显,在这个循环之后,地图是空的。

答案 1 :(得分:1)

在您在其他类中使用之前,您似乎正在删除HashMap中的每个条目。

    Iterator it = map.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        System.out.println(pair.getKey() + " = " + pair.getValue());
        it.remove(); // ***** here *****
    }

不要这样做。

其他问题:以这种方式使用静态字段不是一个好主意,并且可能导致难以调试错误。如果您创建封装良好的类,以干净的面向对象的方式相互交互,那就更好了。

相关问题