1.循环遍历
public class Test {
public static void main(String[] args) {
String [] str={"abc","def","ghi"};
Object[] objects = Test.demo1(str);
for (Object obj:objects
) {
System.out.println(obj);
}
}
/**
* 数组遍历赋值
* @param obj 要拷贝的数组
* @return 返回拷贝后的新数组
*/
public static Object[] demo1(Object [] obj){
Object [] temp = new Object[obj.length];
for (int i = 0; i <obj.length ; i++) {
temp[i]=obj[i];
}
return temp;
}
2.Array.copy
其方法底层还是调用了
System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength));
public static <T> T[] demo2(T[] obj) {
T[] copy = Arrays.copyOf(obj, obj.length);
return copy;
}
3.System.arraycopy(src,srcPos,dest,desPos,length)
* @param src the source array. * @param srcPos starting position in the source array. * @param dest the destination array. * @param destPos starting position in the destination data. * @param length the number of array elements to be copied.
public static Object [] demo3(Object [] obj) {
Object[] copy = new Object[obj.length];
System.arraycopy(obj, 0, copy, 0, obj.length);
return copy;
}
4.clone
public static Object [] demo4(Object [] obj){
Object [] copy = obj.clone();
return copy;
}
clone是浅拷贝
只是复制引用
例:
public static void test(){
String[] str = {"abc", "def", "ghi"};
String[] clone = str.clone();
str[0]="test";
System.out.println(clone[0]);
StringBuilder sb1 = new StringBuilder("abc");
StringBuilder sb2 = new StringBuilder("abc");
StringBuilder sb3 = new StringBuilder("abc");
StringBuilder sb4 = new StringBuilder("abc");
StringBuilder [] sb = {sb1,sb2,sb3,sb4};
StringBuilder[] clone1 = sb.clone();
sb1.append("test");
System.out.println(clone1[0]);
}
结果:
String 是不可改变的,重新赋值时,会在常量池中新创建一个字符串。
clone只是复制了引用,只 是赋值了str数组中的引用,当str[0]的引用改变,clone的引用不变,结果还是“abc”,sb数组证明了这一点。