[英]Is it possible to store double[][] array in ArrayList<double[][]> in JAVA?
[英]transfer arraylist to double array[0] in java
我有这个代码:
public class Test{
arrayList<String> list = new ArrayList<String>();
String[][] temp_list;
public static void main(String[] args)
{
String temp = list.get(0);
temp_list[0] = temp.split(" ");
}
}
我想将“列表”中的第一项转移到temp_list [0]中。编译成功,但是运行时出现错误。这是错误:
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:this line=>temp_list[0] = temp.split(" ");)
有人可以帮助我吗?
您需要先初始化temp_list,然后再使用它。 您需要指定数组的大小。 例如:
int sizeOfArray = 5;
String[][] temp_list = new String[sizeOfArray][];
这是因为您尚未为temp_list
分配任何2D数组。 (分割结果应存储在哪个数组中?)
这是您的代码段的有效版本。
import java.util.ArrayList;
public class Test {
static ArrayList<String> list = new ArrayList<String>();
static String[][] temp_list;
public static void main(String[] args) {
list.add("hello wold");
// allocate memory for 10 string-arrays.
temp_list = new String[10][]; <-----------
String temp = list.get(0);
temp_list[0] = temp.split(" ");
}
}
由于list声明为类的成员变量,而main是静态方法,因此该代码将无法编译。
按照书面说明,list也没有添加任何内容,因此对list.get(0)的调用将引发Exception(尽管不是null指针)。
temp_list数组未在给定的代码中分配(没有新的),因此尝试将其赋值将引发空指针异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.