java char数组转string数组_Java char[] 数组转为 String 的两种方式

参考:

代码

public static void main(String[] args) {

char[] myString = new char[] {'T', 'H', 'I', 'S', ' ', 'I', 'S', ' ', 'T', 'E', 'S', 'T'};

String output1 = new String(myString); // 直接用构造器

System.out.println("output1 : " + output1);

String output2 = String.valueOf(myString); // valueOf 方法

System.out.println("\noutput2 : " + output2);

}

输出

output1 : THIS IS TEST

output2 : THIS IS TEST

JDK 源码

第二种方法 valueOf() 内部调用的是第一种 String()

public static String valueOf(char data[]) {

return new String(data);

}

而 String() 的内部是

public String(char value[]) {

this.value = Arrays.copyOf(value, value.length);

}

再看 Arrays.copyOf()

public static char[] copyOf(char[] original, int newLength) {

char[] copy = new char[newLength];

System.arraycopy(original, 0, copy, 0,

Math.min(original.length, newLength)); // 在 System 类中定义

return copy;

}

System.arraycopy() 在 System 类中被定义为一个 native 方法,具体实现与平台有关。

public static native void arraycopy(Object src, int srcPos,

Object dest, int destPos,

int length);

补充

从运行效果来看, System.arraycopy() 比自己用循环逐个地拷贝要快10~20倍

float[][] foo = mLoadMillionsOfPoints(); // result is a float[1200000][9]

float[][] fooCpy = new float[foo.length][foo[0].length];

long lTime = System.currentTimeMillis();

System.arraycopy(foo, 0, fooCpy, 0, foo.length);

System.out.println("native duration: " + (System.currentTimeMillis() - lTime) + " ms");

lTime = System.currentTimeMillis();

for (int i = 0; i < foo.length; i++)

{

for (int j = 0; j < foo[0].length; j++)

{

fooCpy[i][j] = foo[i][j];

}

}

System.out.println("System.arraycopy() duration: " + (System.currentTimeMillis() - lTime) + " ms");

for (int i = 0; i < foo.length; i++)

{

for (int j = 0; j < foo[0].length; j++)

{

if (fooCpy[i][j] != foo[i][j])

{

System.err.println("ERROR at " + i + ", " + j);

}

}

}

输出

System.arraycopy() duration: 1 ms

loop duration: 16 ms

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值