简单问题在线给分:怎样将一个byte[]的值拷贝给另一个byte[]

ly_88 2002-05-22 09:52:44
怎样将一个byte[]的值拷贝给另一个byte[]
...全文
2944 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
qiaojiannan 2002-05-22
  • 打赏
  • 举报
回复
byte[] a = (byte[])(b.clone());
alphazhao 2002-05-22
  • 打赏
  • 举报
回复
faint
哪有楼上那么复杂?
一个System.arraycopy就行了
System.arraycopy(byte[] A,int i,byte[] B,int j,int length);
意思是从数组A第i个(即A[i]处,含A[i])开始copy长度为length个的byte数据到数组B从第j个开始(即B[j]处,含B[j])覆盖!
hyhong_h 2002-05-22
  • 打赏
  • 举报
回复
System.arrayCopy()方法不是用循环实现的,速度比用循环拷贝要快得多。
山卜居士 2002-05-22
  • 打赏
  • 举报
回复
如果已知byte[] b;

则 byte[] a = (byte[])(b.clone());
Doctor11971 2002-05-22
  • 打赏
  • 举报
回复
byte[] a, b;
...
for(int i=0; i<a.length; i++)
b[i] = a[i];

byte[] a,b;
System.arrayCopy(b,0,a,0,a.length);

都可以.
循环是各种编成方式都经常采用的手法.而第二种是面向对象编成中的方便之处,在java中有System.arraycopy(Object src, int src_position, Object dst, int dst_position, int length) 这样一个方法,而byte又是对象,所以这样一来就不用自己写了,只要作为参数填写就ok了.
horseliu 2002-05-22
  • 打赏
  • 举报
回复
byte[] a,b;
System.arrayCopy(b,0,a,0,a.length);
yanyanem 2002-05-22
  • 打赏
  • 举报
回复

可运行, jbuilder 3 jdk1.2

package csdn;

public class MyClass5 {

public MyClass5() {
}

public static void main(String[] args) {
MyClass5 myClass5 = new MyClass5();
myClass5.invokedStandalone = true;

myClass5.test ();

}
private boolean invokedStandalone = false;

void test(){
byte[] a={1,0,1,0,1};
byte[] b=new byte[a.length];

System.arraycopy (a,0,b,0,a.length);

try{
System.out.println ("b- "+byte_to_string (b));
}catch( Exception e) {}

}

static String byte_to_string ( byte[] in )
throws Exception
{
String result = "" ;

if (in == null) return null;

for (int i=0;i<in.length; i++ )
{
result = result + in[i] ;
}

return result ;
}

}
aiaiok 2002-05-22
  • 打赏
  • 举报
回复
楼上说得对。
SHIZUMARU 2002-05-22
  • 打赏
  • 举报
回复
byte[] a, b;
...
for(int i=0; i<a.length; i++)
b[i] = a[i];
山卜居士 2002-05-22
  • 打赏
  • 举报
回复
实际上arraycopy是调用JNI的一个本地方法:
static void cpchars(jchar *dst, char *src, int n)
{
int i;
for (i = 0; i < n; i++) {
dst[i] = src[i];
}
}
它也是用一个一个字符复制过来的。
而用byte[] a = (byte[])(b.clone())是复制一个内存块的方式,应该更快一些才对.

62,630

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧