簡體   English   中英

在Java中將arraylist傳輸到double array [0]

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM