简体   繁体   English

在Java中将arraylist传输到double array [0]

[英]transfer arraylist to double array[0] in java

i have this code: 我有这个代码:

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(" ");
        }
    }

i want to transfer the first item in 'list' into temp_list[0].compiling is success but i got error when i run it.this is the error: 我想将“列表”中的第一项转移到temp_list [0]中。编译成功,但是运行时出现错误。这是错误:

 Exception in thread "main" java.lang.NullPointerException
            at Test.main(Test.java:this line=>temp_list[0] = temp.split(" ");)

anyone can help me? 有人可以帮助我吗?

You need to initialize temp_list before you use it. 您需要先初始化temp_list,然后再使用它。 You need to specify the size of the array. 您需要指定数组的大小。 For example: 例如:

int sizeOfArray = 5;
String[][] temp_list = new String[sizeOfArray][];

This is because you haven't allocated any 2D-array for temp_list . 这是因为您尚未为temp_list分配任何2D数组。 (Which array should the result of split be stored in?) (分割结果应存储在哪个数组中?)

Here's a working version of your snippet. 这是您的代码段的有效版本。

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(" ");
    }
}

This code would will not compile since list is declared as a member variable of the class but main is a static method. 由于list声明为类的成员变量,而main是静态方法,因此该代码将无法编译。

As written, list has nothing added too so the call to list.get(0) will throw an Exception (not null pointer though). 按照书面说明,list也没有添加任何内容,因此对list.get(0)的调用将引发Exception(尽管不是null指针)。

The array temp_list is not allocated (no new) in the code given so trying assign into it will throw a null pointer exception. temp_list数组未在给定的代码中分配(没有新的),因此尝试将其赋值将引发空指针异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM