当我尝试用进程 ID 填充 2D 数组时,我得到 nullpointerException,它是 2D,因为每个系统都有无限的 PID 列表,我最终需要将其返回到我的主代码(现在设置为 void,因为只是一个原型(prototype)测试功能)。
任何想法都会很棒
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
1D 数组。二维数组中的每个元素都需要创建一个一维数组。您已经使用 tempPid
创建了它;只需使用它即可。而不是
for (int j=0; j < tempPid.length; j++) {
pidCollection[i][j] = tempPid[j];
}
直接使用
pidCollection[i] = tempPid;
关于java 多维数组失败并出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15559254/