Arrays.copyOf功能是实现数组的复制,返回复制后的数组。参数是被复制的数组和复制的长度:
package setclass;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class SetTest1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*Array.copyof function test*/
String[] arr=new String[5];
String[] strs1={"123","234","345","456","789"};
//String[] strs2=new String[2];//Two ways to state a array
String[] str2=Arrays.copyOf(strs1, 3);
String[] str3=Arrays.copyOf(strs1, 8);
System.out.println();
for(String ele:str2){
System.out.print(ele+";");
}
System.out.println();
for(String ele:str3){
System.out.print(ele+";");
}
int[] in={1,2,3,4,5};
int[] int1=Arrays.copyOf(in,3);
int[] int2=Arrays.copyOf(in,8);
System.out.println();
for(int ele:int1){
System.out.print(ele+";");
}
System.out.println();
for(int ele:int2){
System.out.print(ele+";");
}
}
}
运行结果是:
123;234;345;
123;234;345;456;789;null;null;null;
1;2;3;
1;2;3;4;5;0;0;0;
说明:复制的长度大于被复制数组的长度,则填充类型默认值,String得默认值是null,int的默认值是0。
数据型态 | 初值 |
byte | 0 |
short | 0 |
int | 0 |
long | 0L |
float | 0.0f |
double | 0.0d |
char | \u0000 |
boolean | false |