Java中 toCharArray() 方法詳解
《Thinking in Java》Chapter11中存在下列代碼
package holding;
import java.util.*;
public class QueueDemo {
public static void printQ(Queue queue) {
while(queue.peek() != null)
System.out.print(queue.remove() + " ");
System.out.println();
}
public static void main(String[] args) {
//Character
Queue<Character> qc = new LinkedList<Character>();
for(char c : "Brontosaurus".toCharArray())
qc.offer(c);
printQ(qc);
}
}
我們經常會使用到 toCharArray() 方法,深層次的查看這個方法,我們來探討一下。下面是Java類庫中給出的代碼。
/**
* 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() {
// Cannot use Arrays.copyOf because of class initialization order issues
char result[] = new char[value.length];
System.arraycopy(value, 0, result, 0, value.length);
return result;
}
分析:將一個字符串轉換成一個 Character 型的字符數組,並且這里面的字符是原封不動的拿進去的,意思就是說,包含一切字符均轉換成相應的字符數組。
將上面的程序修改如下【在改字符串中添加一些空格的】
//: holding/QueueDemo.java
// Upcasting to a Queue from a LinkedList.
package holding;
import java.util.*;
public class QueueDemo {
public static void printQ(Queue queue) {
while(queue.peek() != null)
System.out.print(queue.remove() + " ");
System.out.println();
}
public static void main(String[] args) {
//Character
Queue<Character> qc = new LinkedList<Character>();
for(char c : "Brontosaurus".toCharArray())
qc.offer(c);
printQ(qc);
}
}
得到以下執行效果: