javachar数组转string数组_Javachar[]数组转为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 = pyOf(value, value.length);
}
再看 pyOf()
public static char[] copyOf(char[] original, int newLength) {
html代码转链接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.arraycopy() duration: 1 ms
loop duration: 16 ms

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。