本文介绍了java多维数组因空指针异常而失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I get nullpointerexception when I try to fill a 2D array with process IDs, it is 2D since there is a unlimited list of PIDs for each system and I need to eventually return that back to my main code (set to void now since just a prototype test function).

任何想法都会很棒

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("
");

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


    }

推荐答案

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

You've created your 2D array, but the array is full of null 1D arrays. Each element in the 2D array needs to have a 1D array created. You've already created it with tempPid; just use it. Instead of

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

就用

pidCollection[i] = tempPid;

这篇关于java多维数组因空指针异常而失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 21:54