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 qc = new LinkedList();

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 qc = new LinkedList();

for(char c : "Brontosaurus".toCharArray())

qc.offer(c);

printQ(qc);

}

}

得到以下执行效果:

8862bb9f6c520f9625a64b77536fe72c.png

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐