Java char[] 数组转为 String 的两种方式

参考:

  1. http://crunchify.com/java-simple-way-to-convert-string-to-char-array/
  2. http://stackoverflow.com/questions/2772152/why-is-system-arraycopy-native-in-java

代码

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("
output2 : " + 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
原文地址:https://www.cnblogs.com/smartjune/p/5495924.html