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

Java 当从另一个类访问公共静态HashMap实例时,该实例返回NULL,即使我在构造函数中填充了值,java,hashmap,Java,Hashmap,我正在尝试创建一个字典来学习Java,它将把wordlist.txt中预定义的单词作为 subterfuge:something intended to misrepresent the true nature of an activity stymie:thwarting and distressing situation; 但是,当我尝试访问声明为publicstatic的ReadToHashmap类的map实例时,它允许我访问,但它总是返回null 如何在所有的HashMap都按照wor

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

subterfuge:something intended to misrepresent the true nature of an activity
stymie:thwarting and distressing situation;
但是,当我尝试访问声明为
publicstatic
ReadToHashmap
类的map实例时,它允许我访问,但它总是返回
null

如何在所有的
HashMap
都按照
wordlist.txt
更新的情况下访问map实例

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);
    }
}

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

在其他类中使用HashMap之前,您似乎要删除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 *****
    }
不要这样做


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

谢谢,删除后效果很好。remove()。这是我犯的愚蠢错误。谢谢,删除后效果很好。删除()。这是我这边愚蠢的错误。我不知道为什么会投反对票,这毫无意义。
    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 *****
    }