数组拷贝
数组拷贝四种方式:
一、 没有隔离性,两个变量只想同一个数组。
public static void main(Strig[] args){ String[] s1 = {"0","1","2"} String[] s2 = s1; s2[0] = "你好"; System.out.println(s1[0]) ;//你好 }
二、s2指向新的数组。
public static void main(String[] args){ String[] s1 = {"0","1","2"} ; String[] s2 = new String[s1.length]; for(int i=0; i<s2.length; i++){ s2[i] = s1[i]; } s2[0] = "你好";
System.out.println(s1[0]) ;//1
}
三、API提供的方法。效率比方法二高
public static void main(String[] args) { String[] s1 = {"0","1","2"}; String[] s2 = new String[s1.length]; System.arraycopy(s1, 0, s2, 0, s1.length); System.out.println(Arrays.toString(s2));//[0,1,2] }
四、Arrays的方法
public static void main(String[] args) { String[] s1 = {"0","1","2"}; String[] s2 = Arrays.copyOf(s1, 3); System.out.println(Arrays.toString(s2));//[0,1,2] }
欢迎点评,共同学习,共同进步