有關數(shù)組的基礎知識,有很多方面,比方說初始化,引用,遍歷,以及一維數(shù)組和二維數(shù)組,今天我們先看看數(shù)組復制的有關內(nèi)容。
來源于牛客網(wǎng)的一道選擇題:
java語言的下面幾種數(shù)組復制方法中,哪個效率最高?
a.for循環(huán)逐一復制
b.system.arraycopy
c.system.copyof
d.使用clone方法
效率:system.arraycopy>clone>arrays.copyof>for循環(huán)
1、system.arraycopy的用法:
1
2
3
4
5
|
public static void arraycopy(object src, int srcpos, object dest, int destpos, int length) |
參數(shù):
src - 源數(shù)組。
srcpos - 源數(shù)組中的起始位置。
dest - 目標數(shù)組。
destpos - 目標數(shù)據(jù)中的起始位置。
length - 要復制的數(shù)組元素的數(shù)量
應用實例:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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后結果:" ); for ( int i= 0 ;i<a2.length;i++){ system.out.print(a2[i]+ " " ); } } } |
運行結果:
2、clone的用法:
java.lang.object類的clone()方法為protected類型,不可直接調(diào)用,需要先對要克隆的類進行下列操作:
首先被克隆的類實現(xiàn)cloneable接口;然后在該類中覆蓋clone()方法,并且在該clone()方法中調(diào)用super.clone();這樣,super.clone()便可以調(diào)用java.lang.object類的clone()方法。
應用實例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
//被克隆的類要實現(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、復制引用和復制對象的區(qū)別
復制引用:是指將某個對象的地址復制,所以復制后的對象副本的地址和源對象相同,這樣,當改變副本的某個值后,源對象值也被改變;
復制對象:是將源對象整個復制,對象副本和源對象的地址并不相同,當改變副本的某個值后,源對象值不會改變;
1
2
3
4
5
6
7
|
cat cat1= new cat( "xiaohua" , 3 ); //源對象 system.out.println( "源對象地址" +cat1); //調(diào)用clone方法,復制對象 cat cat2=(cat)cat1.clone(); cat cat3=(cat)cat1; //復制引用 system.out.println( "復制對象地址:" +cat2); system.out.println( "復制引用地址:" +cat3); |
輸出結果:
可以看出,復制引用的對象和源對象地址相同,復制對象和源對象地址不同
4、arrays.copyof 的用法:
arrays.copyof有十種重載方法,復制指定的數(shù)組,返回原數(shù)組的副本。具體可以查看jdk api
總結
以上就是本文關于java數(shù)組復制的四種方法簡單代碼示例及效率對比的全部內(nèi)容,希望對大家了解數(shù)組復制的有關內(nèi)容有所幫助。
原文鏈接:http://blog.csdn.net/tingzhiyi/article/details/52344845