java multi-dimensional array fails with a nullpointerexception

佐手、 提交于 2021-02-04 21:37:18

问题


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).

Any ideas would be great

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


    }

回答1:


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];
}

just use

pidCollection[i] = tempPid;



回答2:


You need to initialize each element of 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];
}

or, in this case, more simply:

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



回答3:


Short answer, you need to define the second dimention of your array

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

Long answer: You're not abliged to do it on that line, and you can do it on a case by case basis for each first dimention, eg

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

but you need to do it at some point, easiest solution is to define both dimentions at once unless you have a reason not to. Although I think that may not be applicable in this case so use the case by case method



来源:https://stackoverflow.com/questions/15559254/java-multi-dimensional-array-fails-with-a-nullpointerexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!