简体   繁体   English

使用HashMap在我自己的图类中使用NPE

[英]NPE in my own graph class using HashMap

This is for a school project. 这是用于学校项目。 We're supposed to write a program handling graphs with the help of a HashMap. 我们应该编写一个在HashMap的帮助下处理图形的程序。 Each node (or corner?) has a key (which is another node to which we have a connection) and a value (the cost of this connection). 每个节点(或角?)都有一个键(这是我们与之连接的另一个节点)和一个值(此连接的成本)。 I'm almost done and all my test cases works except for the toString() method. 我差不多完成了,除了toString()方法之外,我所有的测试用例都可以工作。 It is supposed to write something like this: 应该写这样的东西:

{(0,1), (2,1)}

This means that 0 and 1 are connected and also 2 and 1 are connected. 这意味着0和1连接,并且2和1也连接。

/**
 * Returns a string representation of this graph.
 * 
 * @return a String representation of this graph
 */
@Override
public String toString() {
    // TODO
    StringBuilder sb = new StringBuilder();
    sb.append("{");
    for (int i = 0; i < edges.length; i++) {
        for (int j = 0; j < edges[i].size(); j++) {

            if (edges[i].containsKey(j)) {
                if (j < edges[i].size() - 1) {
                    sb.append("(" + i + "," + j + "),");
                } else if (j == edges[i].size() - 1) {
                    sb.append("(" + i + "," + j + ")");
                }

            }
        }
        if (i != edges.length - 1) {
            sb.append(", ");
        }
    }
    sb.append("}");
    System.out.println(sb.toString());
    return sb.toString();
}

Since our code structure (the code we started with) has a static size for the HashMap I get a NPE if I make a graph for 5 nodes and only add 3 of them. 由于我们的代码结构(我们开始的代码)的HashMap大小是静态的,因此,如果我为5个节点绘制图形,而仅添加3个节点,则将得到NPE。 When I try to print these I will get a NPE due to edges[i].containsKey(j)) . 当我尝试打印这些时,由于edges[i].containsKey(j))我将获得NPE。

It's possible that you aren't initializing every element of the edges array. 您可能没有初始化edges数组的每个元素。

You can test that the edges index is not null before you even attempt to check if the key is contained. 您甚至可以在尝试检查键是否包含之前,可以测试edge索引是否不为null。

Change: 更改:

if (edges[i].containsKey(j))

To: 至:

if (edges[i] != null && edges[i].containsKey(j))

This is possible because of short-circuit evaluation: 这可能是由于短路评估:

http://en.wikipedia.org/wiki/Short-circuit_evaluation http://zh.wikipedia.org/wiki/短路评估

You also might not even want to enter the nested for-loop if the value is null. 如果该值为空,您甚至可能甚至不想输入嵌套的for循环。 In this situation, wrap the nested for-loop around a condition to ensure edges[i] != null. 在这种情况下,将嵌套的for循环包装在条件周围,以确保edge [i]!= null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM