【问题标题】:java multi-dimensional array fails with a nullpointerexceptionjava 多维数组因空指针异常而失败
【发布时间】:2013-03-21 22:15:18
【问题描述】:

当我尝试用进程 ID 填充 2D 数组时出现 nullpointerexception,它是 2D 的,因为每个系统都有无限的 PID 列表,我最终需要将其返回到我的主代码(现在设置为 void,因为只是一个原型测试函数)。

任何想法都会很棒

private void testfunctionA (List<String> additionalPC) {

    // A 2d array that will contain a list of pids for each system - needs to be strings and not integers
    String[][] pidCollection = new String[additionalPC.size()][];

    // Go through one system at a time
    for (int i=0; i < additionalPC.size(); i++) {

            // Get pids for apple per system
            String listofpids = Driver.exec("ssh " +  additionalPayloads.get(i) + " ps -ef | grep -i apple | grep -v \"grep -i apple\" | awk \\' {print $2}\\'");

            // Works ok for printing for one system
            System.out.println(listofpids);
            // put the list of pids into a string array - they are separated by rows
            String[] tempPid = listofpids.split("\n");

            // Put the string array into the 2d array - put this fails with a NPE
            for (int j=0; j < tempPid.length; j++) {
                    pidCollection[i][j] = tempPid[j];
            }

            System.out.println(pidCollection);


    }

【问题讨论】:

    标签: java multidimensional-array nullpointerexception


    【解决方案1】:

    您已经创建了二维数组,但该数组中充满了null 一维数组。二维数组中的每个元素都需要创建一个一维数组。您已经使用tempPid 创建了它;就用它。而不是

    for (int j=0; j < tempPid.length; j++) {
        pidCollection[i][j] = tempPid[j];
    }
    

    随便用

    pidCollection[i] = tempPid;
    

    【讨论】:

    • 谢谢,它有效!还意识到我不应该像在我的示例中那样打印多维数组。
    【解决方案2】:

    你需要初始化pidCollection的每个元素:

    String[] tempPid = listofpids.split("\n");
    
    pidCollection[i] = new String[tempPid.length];
    
    // Put the string array into the 2d array - put this fails with a NPE
    for (int j=0; j < tempPid.length; j++) {
            pidCollection[i][j] = tempPid[j];
    }
    

    或者,在这种情况下,更简单:

    pidCollection[i] = listofpids.split("\n");
    

    【讨论】:

      【解决方案3】:

      简短的回答,您需要定义数组的第二个维度

      String[][] pidCollection = new String[additionalPC.size()][?????]; //this initialises the` first axis
      

      长答案: 您没有义务在该行执行此操作,您可以针对每个第一维度逐个执行此操作,例如

      pidCollection[i]=new String[tempPid.length] //this initialised the second axis for a particular i
      

      但是您需要在某个时候这样做,最简单的解决方案是一次定义两个维度,除非您有理由不这样做。虽然我认为这可能不适用于这种情况,但请使用个案方法

      【讨论】:

      • 我无法事先知道 PID 列表的大小,因此我无法事先给出固定长度。之前的解决方案奏效了。感谢您的意见
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-05
      • 1970-01-01
      • 2021-12-07
      • 1970-01-01
      • 2011-02-07
      • 2014-12-02
      • 1970-01-01
      相关资源
      最近更新 更多