2012-03-30 181 views
3

我編碼爲我Applictation拋出NullPointerException,我碰到一個要求,在這裏我需要字符串轉換爲字符數組我爲什麼它不在這種情況下

String str_a = "Testing"; 

char c[] = str_a.toCharArray(); 

for (char d : c) { 
    System.out.println(d); 
} 

像我一樣未初始化char c[]

我的問題是,爲什麼不拋出一個NullPointerException,通常應該這樣做這樣

char[] char_array = new char[str_a.length()]; 

char_array = str_a.toCharArray();  

for (char d : c) { 
    System.out.println(d); 
} 

回答

3

toCharArray()的源代碼:

/** 
* Converts this string to a new character array. 
* 
* @return a newly allocated character array whose length is the length 
*   of this string and whose contents are initialized to contain 
*   the character sequence represented by this string. 
*/ 
public char[] toCharArray() { 
    char result[] = new char[count]; // <-- Here is the initialization :) 
    getChars(0, count, result, 0); 
    return result; 
} 
+0

謝謝,這是很好的解釋 – Pawan 2012-03-30 17:54:57

5

因爲str_a.toCharArray();已經初始化並分配了一個合適的字符數組。這個方法返回的東西已經爲你分配和初始化了。

+0

要添加到的是,如果是調用'toCharArray之前分配一個空數組'char_array'( )',原來的數組現在需要GC'd。 – 2012-03-30 17:54:04

+0

*有*位置在目標數組由調用者分配的Java中,但這些API都要求您傳入目標數組作爲參數。例如,請參閱'InputStream.read(...)'。 – 2012-03-30 17:55:12

1

當您立即將str_a.toCharArray()的結果指定爲char_array時,無需初始化char_array

在你的第二個例子,你創建它扔掉就因爲你然後計算str_a.toCharArray()空數組。方法toCharArray計算數組的值並將其返回,因此您不必自己創建一個數組。

1

這兩種方法都工作得很好。第一個將新數組定義爲char數組,第二個創建一個空數組並將其設置爲等於char數組;當你認真對待它時,兩者都是一樣的,但第二條只是有更多的線條。

您也可以節省一些時間,做:

for(char c : str_a.toCharArray()){ 
    System.out.println(c); 
} 
0

string.toCharArray()返回一個新的char[]的方法,無需別人先初始化變量的東西。

逸岸,如果你離開你的代碼...

char[] char_array = new char[str_a.length()]; 
char_array = str_a.toCharArray(); 

這將變量初始化爲char[]的一個實例,然後把那個實例上移開就非常下一行。這是低效的,毫無意義的,令人費解的。

0

在代碼中所示使用的是變量c但不是C必須使用char_arra

char[] char_array = new char[str_a.length()]; 

char_array = str_a.toCharArray();  

for (char d : char_array) { 
      System.out.println(d); 
     } 
相關問題