java數(shù)組復(fù)制的四種方法效率對(duì)比
有關(guān)數(shù)組的基礎(chǔ)知識(shí),有很多方面,比方說(shuō)初始化,引用,遍歷,以及一維數(shù)組和二維數(shù)組,今天我們先看看數(shù)組復(fù)制的有關(guān)內(nèi)容。
來(lái)源于牛客網(wǎng)的一道選擇題:
JAVA語(yǔ)言的下面幾種數(shù)組復(fù)制方法中,哪個(gè)效率最高?
A.for循環(huán)逐一復(fù)制
B.System.arraycopy
C.System.copyof
D.使用clone方法
效率:System.arraycopy>clone>Arrays.copyOf>for循環(huán)
1、System.arraycopy的用法:
public static void arraycopy(Object src,
int srcPos,
Object dest,
int destPos,
int length)
參數(shù):
src - 源數(shù)組。
srcPos - 源數(shù)組中的起始位置。
dest - 目標(biāo)數(shù)組。
destPos - 目標(biāo)數(shù)據(jù)中的起始位置。
length - 要復(fù)制的數(shù)組元素的數(shù)量
應(yīng)用實(shí)例:
public class Main{
public static void main(String[] args) {
int[] a1={1,2,3,4,5,6};
int[] a2={11,12,13,14,15,16};
System.arraycopy(a1, 2, a2, 3, 2);
System.out.print("copy后結(jié)果:");
for(int i=0;i<a2.length;i++){
System.out.print(a2[i]+" ");
}
}
}
運(yùn)行結(jié)果:

2、clone的用法:
java.lang.Object類的clone()方法為protected類型,不可直接調(diào)用,需要先對(duì)要克隆的類進(jìn)行下列操作:
首先被克隆的類實(shí)現(xiàn)Cloneable接口;然后在該類中覆蓋clone()方法,并且在該clone()方法中調(diào)用super.clone();這樣,super.clone()便可以調(diào)用java.lang.Object類的clone()方法。
應(yīng)用實(shí)例:
//被克隆的類要實(shí)現(xiàn)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);
//調(diào)用clone方法
Cat cat2=(Cat)cat1.clone();
System.out.println(cat2);
}
}
3、復(fù)制引用和復(fù)制對(duì)象的區(qū)別
復(fù)制引用:是指將某個(gè)對(duì)象的地址復(fù)制,所以復(fù)制后的對(duì)象副本的地址和源對(duì)象相同,這樣,當(dāng)改變副本的某個(gè)值后,源對(duì)象值也被改變;
復(fù)制對(duì)象:是將源對(duì)象整個(gè)復(fù)制,對(duì)象副本和源對(duì)象的地址并不相同,當(dāng)改變副本的某個(gè)值后,源對(duì)象值不會(huì)改變;
Cat cat1=new Cat("xiaohua",3);//源對(duì)象
System.out.println("源對(duì)象地址"+cat1);
//調(diào)用clone方法,復(fù)制對(duì)象
Cat cat2=(Cat)cat1.clone();
Cat cat3=(Cat)cat1;//復(fù)制引用
System.out.println("復(fù)制對(duì)象地址:"+cat2);
System.out.println("復(fù)制引用地址:"+cat3);
輸出結(jié)果:

可以看出,復(fù)制引用的對(duì)象和源對(duì)象地址相同,復(fù)制對(duì)象和源對(duì)象地址不同
4、Arrays.copyOf 的用法:
Arrays.copyOf有十種重載方法,復(fù)制指定的數(shù)組,返回原數(shù)組的副本。具體可以查看jdk api
總結(jié)
以上就是本文關(guān)于java數(shù)組復(fù)制的四種方法簡(jiǎn)單代碼示例及效率對(duì)比的全部?jī)?nèi)容,希望對(duì)大家了解數(shù)組復(fù)制的有關(guān)內(nèi)容有所幫助。
相關(guān)文章
Java在Excel中創(chuàng)建多級(jí)分組、折疊或展開(kāi)分組的實(shí)現(xiàn)
這篇文章主要介紹了Java在Excel中創(chuàng)建多級(jí)分組、折疊或展開(kāi)分組的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
springcloud使用feign調(diào)用服務(wù)時(shí)參數(shù)內(nèi)容過(guò)大問(wèn)題
詳解Spring boot上配置與使用mybatis plus
解決org.springframework.context.ApplicationContextException報(bào)錯(cuò)的
Java SimpleDateFormat中英文時(shí)間格式化轉(zhuǎn)換詳解

