【问题标题】:Adding and getting Comm Ports from RXTX从 RXTX 添加和获取 Comm 端口
【发布时间】:2015-12-22 19:11:46
【问题描述】:

我目前正在处理一个需要与通过 commport 连接的设备进行通信的项目。我在下面有一个函数,它搜索串行端口,将它们添加到哈希图中,然后返回哈希图。我注意到一个问题,每当我尝试从 HashMap 中获取某些东西时,它都会给出 java.lang.nullPointerException 我是否试图从地图中错误地获取端口?如果我需要发布更多代码,请告诉我。

private Enumeration ports = null;
public HashMap<String, CommPortIdentifier> searchForPorts() {
        ports = CommPortIdentifier.getPortIdentifiers();
        while (ports.hasMoreElements()) {
            CommPortIdentifier curPort = (CommPortIdentifier) ports.nextElement();
            if (curPort.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                System.out.println("Adding: " + curPort.getName() + "-" + curPort);  
                portMap.put(curPort.getName(), curPort);
                System.out.println(portMap.get(curPort.getName())); //works: prints out gnu.io.CommPortIdentifier@9f116cc
            }
        }
        log.fine("Successfully looked for ports");
        Iterator it = portMap.entrySet().iterator();
        String s="";
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry) it.next();
            s = pair.getKey().toString();
            System.out.println(s); //prints out COM24 like it should
            it.remove();
        }
        System.out.println(portMap.get(s)); //Prints out null??
        return portMap;
    }

部分代码取自here

【问题讨论】:

  • 您填充地图,打印文本,清空地图,然后尝试从刚刚清空的地图中获取元素。
  • @jhamon 我在哪里清空它?我从迭代器中删除元素,而不是 HashMap。
  • javadoc 中所述:从基础集合中移除此迭代器返回的最后一个元素
  • 如何在不移除元素的情况下遍历 HashMap?
  • 查看我之前评论中的链接,Remove 正上方的部分。提示:它是next()。另一种解决方案是使用 foreach 循环而不是 while

标签: java iterator hashmap


【解决方案1】:

您使用it.remove() 删除地图中的元素,正如javadoc 中所述:从基础 集合中删除此迭代器返回的最后一个元素

要使用迭代器访问下一个元素,您只需使用it.next()(假设还有剩余元素)。

另一种解决方案是使用这样的 foreach 循环:

for(Map.Entry pair : portMap.entrySet()){
    s = pair.getKey().toString();
    System.out.println(s);
}

【讨论】: