OnJava8-Examples/arrays/CopyingArrays.java

46 lines
1.5 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// arrays/CopyingArrays.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2015-06-15 17:47:35 -07:00
// Using System.arraycopy()
import java.util.*;
public class CopyingArrays {
public static void main(String[] args) {
int[] i = new int[7];
int[] j = new int[10];
Arrays.fill(i, 47);
Arrays.fill(j, 99);
2015-11-03 12:00:44 -08:00
System.out.println("i = " + Arrays.toString(i));
System.out.println("j = " + Arrays.toString(j));
2015-06-15 17:47:35 -07:00
System.arraycopy(i, 0, j, 0, i.length);
2015-11-03 12:00:44 -08:00
System.out.println("j = " + Arrays.toString(j));
2015-06-15 17:47:35 -07:00
int[] k = new int[5];
Arrays.fill(k, 103);
System.arraycopy(i, 0, k, 0, k.length);
2015-11-03 12:00:44 -08:00
System.out.println("k = " + Arrays.toString(k));
2015-06-15 17:47:35 -07:00
Arrays.fill(k, 103);
System.arraycopy(k, 0, i, 0, k.length);
2015-11-03 12:00:44 -08:00
System.out.println("i = " + Arrays.toString(i));
2015-06-15 17:47:35 -07:00
// Objects:
Integer[] u = new Integer[10];
Integer[] v = new Integer[5];
Arrays.fill(u, 47);
Arrays.fill(v, 99);
2015-11-03 12:00:44 -08:00
System.out.println("u = " + Arrays.toString(u));
System.out.println("v = " + Arrays.toString(v));
2015-06-15 17:47:35 -07:00
System.arraycopy(v, 0, u, u.length/2, v.length);
2015-11-03 12:00:44 -08:00
System.out.println("u = " + Arrays.toString(u));
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
i = [47, 47, 47, 47, 47, 47, 47]
j = [99, 99, 99, 99, 99, 99, 99, 99, 99, 99]
j = [47, 47, 47, 47, 47, 47, 47, 99, 99, 99]
k = [47, 47, 47, 47, 47]
i = [103, 103, 103, 103, 103, 47, 47]
u = [47, 47, 47, 47, 47, 47, 47, 47, 47, 47]
v = [99, 99, 99, 99, 99]
u = [47, 47, 47, 47, 47, 99, 99, 99, 99, 99]
2015-09-07 11:44:36 -06:00
*/