[英]java multi-dimensional array fails with a nullpointerexception
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). 当我尝试使用进程ID填充2D数组时,我得到nullpointerexception,它是2D,因为每个系统都有一个无限的PID列表,我需要最终将它返回到我的主代码(现在设置为void,因为只是一个原型测试功能)。
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);
}
You've created your 2D array, but the array is full of null
1D arrays. 您已经创建了2D数组,但数组中充满了null
1D数组。 Each element in the 2D array needs to have a 1D array created. 2D阵列中的每个元素都需要创建一维数组。 You've already created it with tempPid
; 你已经用tempPid
创建了它; just use it. 只是使用它。 Instead of 代替
for (int j=0; j < tempPid.length; j++) {
pidCollection[i][j] = tempPid[j];
}
just use 只是用
pidCollection[i] = tempPid;
You need to initialize each element of pidCollection: 您需要初始化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");
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 虽然我认为在这种情况下可能不适用,但请使用个案方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.