java tochararray_Java中toCharArray()方法

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);

}

}

得到以下执行效果:

bfa541b2f3ea57ef0e81a31450c9aaf0.png

标签:Queue,Java,System,queue,qc,toCharArray,方法,public

来源: https://www.cnblogs.com/Rosemajor/p/12195961.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值