Java多维数组因nullpointerException失败 [英] java multi-dimensional array fails with a nullpointerexception

查看:40
本文介绍了Java多维数组因nullpointerException失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试用进程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("\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);


    }

推荐答案

您已经创建了2D数组,但是该数组充满了 null 一维数组.2D数组中的每个元素都需要创建一个1D数组.您已经使用 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多维数组因nullpointerException失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆