简体   繁体   中英

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:

 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. 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 . (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.

As written, list has nothing added too so the call to list.get(0) will throw an Exception (not null pointer though).

The array temp_list is not allocated (no new) in the code given so trying assign into it will throw a null pointer exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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