2011-07-30 28 views
0

雙數組[0]我有這樣的代碼:轉移的ArrayList在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] .compiling是成功的,但我得到的錯誤時,我運行它。這是錯誤:

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

任何人都可以幫助我嗎?

回答

0

這是因爲您還沒有爲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(" "); 
    } 
} 
+0

太棒了!!!它的工作now.yes,我沒有分配的temp_list.thanks哥們的大小! – Roubie

+0

沒問題,不客氣。 – aioobe

0

您需要在使用它之前初始化temp_list。您需要指定數組的大小。例如:

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

指定的指數看起來倒退。 – 2011-07-30 06:51:09

+0

修正了錯誤。 –

0

這段代碼不會編譯,因爲list被聲明爲類的成員變量,但main是靜態方法。

正如所寫,list沒有添加任何內容,所以對list.get(0)的調用將拋出一個Exception(儘管不是空指針)。

在給定的代碼中未分配數組temp_list(不是新的),所以試圖分配它將拋出空指針異常。