Java arraycopy方法
} 1.您能解释一下为什么相同的代码块不能用于不同的基元类型(使用char,但不能使用int和String)Java arraycopy方法,java,Java,} 1.您能解释一下为什么相同的代码块不能用于不同的基元类型(使用char,但不能使用int和String)System.out.println(新字符串(copyTo))与字符一起使用,但与字符串不一起使用。类似地System.out.println(copyTo)用于char但不用于String和int 为什么相同的基元类型在相同的代码中表现不同System.out.println(“打印字符:+(copyTo))不起作用,但系统.out.println(copyTo) 我没有发现任何材料表
System.out.println(新字符串(copyTo))代码>与字符一起使用,但与字符串不一起使用。类似地System.out.println(copyTo)代码>用于char但不用于String和int
为什么相同的基元类型在相同的代码中表现不同<代码>System.out.println(“打印字符:+(copyTo))代码>不起作用,但系统.out.println(copyTo)代码>
我没有发现任何材料表明arraycopy
方法仅适用于char数据类型。您只是打印了错误的结果
public class ArrayCoping {
public static void main(String[] args) {
// Copied from Java Docs
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
//Experimenting
System.out.println("Printing char: " + new String(copyTo));
System.out.println("Printing char: " + (copyTo));
System.out.println(copyTo);
// STRING
String[] stringSrc = { "abc", "def", "ghi", "jkl", "mno", "pqr" };
String[] stringDst = new String[4];
System.arraycopy(stringSrc, 1, stringDst, 0, 4);
//Error System.out.println(new String(stringDst));
System.out.println("Printing string: " + (stringDst));
System.out.println(stringDst);
// INT
int[] numSrc = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
int[] numDst = new int[4];
System.arraycopy(numSrc, 1, numDst, 0, 4);
//Error System.out.println(new int (numDst));
System.out.println("Printing int: " + (numDst));
System.out.println(numDst);
}
恰好可以工作,因为String
有一个构造函数,它接受char[]
如果要打印数组,请使用arrays.toString(array)
比如:
我不明白你的问题。到底是什么问题?请用一个问题做一个简单的例子。这里似乎至少有3到4个问题。//Error System.out.println(新字符串(stringDst))代码>。。因为您必须解析String
而不是String[]
arraycopy方法无法处理int和String。String
不是基元类型。
System.out.println(new String(copyTo));
System.out.println(Arrays.toString(stringDst));
...
System.out.println(Arrays.toString(numDst));