提交 00568e88 编写于 作者: cherry_xixi's avatar cherry_xixi

java实现数组复制的方法

上级 0698c5c1
读取文件的方法:
/**********************************读取文件的方法:
1、按字节读取文件内容:(模板)
public class ReadFromFile{
/**
......@@ -159,4 +159,48 @@ public static void appendMethodA(String fileName, String content) {
e.printStackTrace();
}
}
/********************************数组复制的方法:
1. System.arraycopy(Object src,int srcPos,Object dest,int destPos,int length)
//源数组、源数组中的起始位置、目标数组、目标数组中的位置、复制长度
2.Arrays.copyOf(Object src,int len)
//源数组、复制长度(新数组长度,如果新数组的长度超过原数组的长度,则保留数组默认值)
Arrays的copyOf()方法传回的数组是新的数组对象,改变传回数组中的元素值,不会影响原来的数组。
import java.util.Arrays;
public class ArrayDemo {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = Arrays.copyOf(arr1, 5);//1 2 3 4 5
int[] arr3 = Arrays.copyOf(arr1, 10);//1 2 3 4 5 0 0 0 0 0
}
}
3.使用clone方法
java.lang.Object类的clone()方法为protected类型,不可直接调用,需要先对要克隆的类进行下列操作:
首先被克隆的类实现Cloneable接口;然后在该类中覆盖clone()方法,并且在该clone()方法中调用super.clone();这样,super.clone()便可以调用java.lang.Object类的clone()方法。
//被克隆的类要实现Cloneable接口
class Cat implements Cloneable
{
private String name;
private int age;
public Cat(String name,int age)
{
this.name=name;
this.age=age;
}
//重写clone()方法
protected Object clone()throws CloneNotSupportedException{
return super.clone() ;
}
}
public class Clone {
public static void main(String[] args) throws CloneNotSupportedException {
Cat cat1=new Cat("xiaohua",3);
System.out.println(cat1);
//调用clone方法
Cat cat2=(Cat)cat1.clone();//复制对象,cat2和cat1指向不同地址
Cat cat3=(Cat)cat1;//复制引用,cat3和cat1指向同一个地址
}
}
/****************************************
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册