有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

返回空值的java HashMap

嘿伙计们这是我放mapTable时循环中的代码。得到(“NN”)。它给出了正确的值,但在循环外的print语句中,它给出了null。请帮忙

Map<String,String> mapTable=new HashMap<String,String>();
    while((line2=br1.readLine())!=null)
    {
        if((!line2.trim().isEmpty())&&Character.isDigit(line2.charAt(0)))
        {
        String[] tmp=line2.split("\t");
        mapTable.put(tmp[1].trim(),tmp[2].trim());
        System.out.println("MAP-----"+tmp[1]+ " ->  "+tmp[2]+" ex "+mapTable.get("NN"));
        }   
    }
    printMap(mapTable);
    System.out.println("CHECKING-------> "+mapTable.get("NN"));


This is the output:

MAP-----NN  ->  n ex n
MAP-----NNS  ->  n ex n
MAP-----NNP  ->  n ex n
MAP-----NNPS  ->  n ex n
MAP-----PDT  ->   ex n
and so on..
JJ = adj
NN = n
WRB = adv
LS = 
PRP = prp
DT = dt
FW = pw

CHECKING-------> null

打印地图功能:

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

共 (1) 个答案

  1. # 1 楼答案

    删除行:

    it.remove(); // avoids a ConcurrentModificationException
    

    在这一行中,您将从地图中删除所有元素