关于System.arraycopy()方法的一个发现,不知道各位是否认可,或是偶的理解有误也肯请帮忙指正
第一个程序如下,运行也完全无误
public class ArrayCopy
{
public static void main(String[] args)
{
String totalBookNames[] = new String[1000];
for(int i=0;i<totalBookNames.length;++i)
{
totalBookNames[i]="图书"+i;
}
String lendBookNames[] = new String[15];
System.arraycopy(totalBookNames,8,lendBookNames,0,15);
System.out.println("借出的图书列表如:");
for(int i=0;i<lendBookNames.length;++i)
{
System.out.println(lendBookNames[i]);
}
}
}
下面给出第二个使用该方法的程序,运行有错误
import java.io.*;
public class AcceptInMessage
{
public static void main(String[] args)
{
char engChar[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z'};
int arcChar[] = {};
System.out.println(engChar.length);
System.arraycopy(engChar,0,arcChar,0,5);
for(int i=0;i<=25;i++)
{
System.out.print(engChar[i]);
}
System.out.println();
}
}
运行错误提示信息如下(编译正确)
Exception in thread "main" java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at AcceptInMessage.main(AcceptInMessage.java:11)
不知道这里作何解释?难道说System.arraycopy()方法操作的数组只能应用于用new方法创建的数组吗?
问题点数:20、回复次数:5Top
1 楼yema55(我不会编程)回复于 2005-02-03 15:21:20 得分 4
int arcChar[] = {}, 长度为0的数组Top
2 楼yema55(我不会编程)回复于 2005-02-03 15:26:33 得分 4
sorry,原数组与目的数组应该同类型,不可转型Top
3 楼wang_mh(于阳)回复于 2005-02-03 15:43:05 得分 5
//import java.io.*;
public class AcceptInMessage
{
public static void main(String[] args)
{
char engChar[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z'};
char arcChar[] = new char[26];
System.out.println(engChar.length);
System.arraycopy(engChar,0,arcChar,0,5);
for(int i=0;i<=25;i++)
{
System.out.print(engChar[i]);
}
System.out.println();
}
}
这样就可以执行了,可能两个原因1、数组长度为0,2、数组类型不同Top
4 楼gobin()回复于 2005-02-03 15:46:52 得分 2
public static void arraycopy(Object src,
int srcPos,
Object dest,
int destPos,
int length)
Parameters:
src - the source array.
srcPos - starting position in the source array.
dest - the destination array.
destPos - starting position in the destination data.
length - the number of array elements to be copied.
Throws:
IndexOutOfBoundsException - if copying would cause access of data outside array bounds.
ArrayStoreException - if an element in the src array could not be stored into the dest array because of a type mismatch.
NullPointerException - if either src or dest is null.
Top
5 楼gobin()回复于 2005-02-03 15:50:17 得分 5
public class AcceptInMessage
{
public static void main(String[] args)
{
char[] engChar = {'a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z'};
char[] arcChar = {'v','w','x','y','z'};
System.out.println(engChar.length);
try {
System.arraycopy(engChar,0,arcChar,0,3);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
for(int i=0;i<arcChar.length;i++)
{
System.out.print(arcChar[i]);
}
}
}
}
执行
26
abcyz
数组类型要相同,长度可以不同Top




