数组的三种扩容方法
1.创建数组时必须显式指定长度,并在创建之后不可更改长度。 2.扩容的思路: 创建大于原数组长度的新数组。 将原数组中的元素依次复制到新数组中。
扩容方法
一循环将原数组中的所有元素逐一赋值给新数组。
public class TestExpand{
public static void main(String
[] args
){
int[] oldnums
= new int[]{11,22,33,44};
int[] newnums
= new int[old
.length
*2];
for(int i
= 0;i
<oldnums
.length
;i
++){
newnums
[i
] = oldnums
[i
];
}
for(int i
=0 ;i
<newnums
.length
;i
++){
System
.out
.println(newnums
[i
]);
}
}
}
二System.arraycopy ( 原数组,原数组起始,新数组,新数组起始,长度)
public class TestExpand2{
public static void main(String
[] args
){
int[] oldnums
= new int[]{11,22,33,44};
int[] newnums
= new int[oldnums
.length
*2];
System
.arraycopy(oldnums
,0,newnums
,0,oldnums
.length
);
for(int i
=0 ;i
<newnums
.length
;i
++){
System
.out
.println(newnums
[i
]);
}
}
}
三使用java的util包的Arrays类的copyOf(原数组名,新数组长度)方法来进行复
import java
.util
.Arrays
;
public class test{
public static void main(String
[] args
){
int[] oldnums
= new int[]{11,22,33,44};
int[] newnums
= Arrays
.copyOf(oldnums
,oldnums
.length
*2);
for(int i
=0 ;i
<newnums
.length
;i
++){
System
.out
.println(newnums
[i
]);
}
}
}
其他介绍一下Arrays.copyOf()和System.arrayCopy()方法的区别:
System.arraycopy();
1、功能强大,使用灵活。
2、参数多,容易发生异常。
3、需要较复杂的数组复制时使用。
Arrays.copyOf()
1、参数少,没有异常。
2、功能有限,需要import。
3、需要普通的数组扩容,缩容时使用。