<Java>Java数组的深拷贝与浅拷贝
2014-11-30 23:34
344 查看
1.Java数组深拷贝,也就是引用传递,影响原来的值,可以直接进行赋值:
int arraySource[] = {1,2,3};
int length = arraySource.length;
int arrayDest[] = new int[length];
arrayDest = arraySource;
对arrayDest的操作影响arraySource的值。
2.Java数组浅拷贝,值传递,不影响原来的值:
system.arrayCopy(Object src,int srcPos,Object dest,int destPos,int length);
system.arrayCopy(arraySource,0,arrayDest,0,length);
对arrayDest的操作不影响arraySource的值。
另有一种clone方法,未曾研究。
栗子
输出:
getArray:
412
original array:
412
getAy:
312
original array:
412
int arraySource[] = {1,2,3};
int length = arraySource.length;
int arrayDest[] = new int[length];
arrayDest = arraySource;
对arrayDest的操作影响arraySource的值。
2.Java数组浅拷贝,值传递,不影响原来的值:
system.arrayCopy(Object src,int srcPos,Object dest,int destPos,int length);
system.arrayCopy(arraySource,0,arrayDest,0,length);
对arrayDest的操作不影响arraySource的值。
另有一种clone方法,未曾研究。
栗子
public class FartherJava { public FartherJava() { buf =new short[3]; for(short i = 0;i<3;i++) { buf[i] = i; } private short[] buf; public short[] retArray() { return buf; } public int getArrayLength() { return buf.length; } public void printArray() { System.out.println(); System.out.println("original array:"); for (short i : buf) { System.out.print(i); } } public static void main(String args[]) { FartherJava m = new FartherJava(); short[] getArray = new short[10]; getArray = m.retArray(); int len = m.getArrayLength(); getArray[0] = 4; System.out.println("getArray:"); for(short s : getArray) { System.out.print(s); } m.printArray(); System.out.println(); short[] getAy = new short[len]; System.arraycopy(m.retArray(), 0, getAy, 0, 3); getAy[0] = 3; System.out.println("getAy:"); for (short s : getAy) { System.out.print(s); } m.printArray(); } }
输出:
getArray:
412
original array:
412
getAy:
312
original array:
412
相关文章推荐
- <Java>函数的参数是数组
- <Java>Java数组的声明与初始化
- <一>java数据结构与算法 数组
- 在Java中将数据库查询结果保存为List<Map>类型的JavaScript数组文件
- <为知更新>java里的throws 和 try-catch 的用法
- JavaBean中的<jsp:useBean>标签
- 程序员_Java初级<四>数组、进制转换函数
- <BEA-000386> <Server subsystem failed. Reason: java.lang.AssertionError: java.lang.reflect.Invocatio
- <黑马程序员>枚举--(java基础加强1.5新特性)
- 数组操作大全<Java实现>
- Java中的 File类对文件 路径分割符不敏感! <发现>
- <转>java jsp JXL调用模版导出Excel
- <java>No enclosing instance of type GraphicFrame is accessible. Must qualify the allocation with an
- <杂谈1002>HTML作为GUI前段,Java/NDK作为业务后端开发方式总结
- <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>会报错
- 在JavaScript中实现类似Java中List<Map>类型的数组
- <Thinking in Java>读书进度贴
- JAVA 运算符 >> >>> <<
- Java笔记1 Java编程基础<3>数组运用
- <转> java内存动态编译执行