| 22 | public class ArrayCopying { |
| 23 | public static final int SZ = 15; |
| 24 | public static void main(String[] args) { |
| 25 | int[] a1 = new int[SZ]; |
| 26 | Arrays.setAll(a1, new Count.Integer()::get); |
| 27 | show("a1", a1); |
| 28 | int[] a2 = Arrays.copyOf(a1, a1.length); // [1] |
| 29 | // Prove they are distinct arrays: |
| 30 | Arrays.fill(a1, 1); |
| 31 | show("a1", a1); |
| 32 | show("a2", a2); |
| 33 | |
| 34 | // Create a shorter result: |
| 35 | a2 = Arrays.copyOf(a2, a2.length/2); // [2] |
| 36 | show("a2", a2); |
| 37 | // Allocate more space: |
| 38 | a2 = Arrays.copyOf(a2, a2.length + 5); |
| 39 | show("a2", a2); |
| 40 | |
| 41 | // Also copies wrapped arrays: |
| 42 | Integer[] a3 = new Integer[SZ]; // [3] |
| 43 | Arrays.setAll(a3, new Count.Integer()::get); |
| 44 | Integer[] a4 = Arrays.copyOfRange(a3, 4, 12); |
| 45 | show("a4", a4); |
| 46 | |
| 47 | Sub[] d = new Sub[SZ/2]; |
| 48 | Arrays.setAll(d, Sub::new); |
| 49 | // Produce Sup[] from Sub[]: |
| 50 | Sup[] b = |
| 51 | Arrays.copyOf(d, d.length, Sup[].class); // [4] |
| 52 | show(b); |
| 53 | |
| 54 | // This "downcast" works fine: |
| 55 | Sub[] d2 = |
| 56 | Arrays.copyOf(b, b.length, Sub[].class); // [5] |
| 57 | show(d2); |
| 58 | |
| 59 | // Bad "downcast" compiles but throws exception: |
| 60 | Sup[] b2 = new Sup[SZ/2]; |
| 61 | Arrays.setAll(b2, Sup::new); |
| 62 | try { |
| 63 | Sub[] d3 = Arrays.copyOf( |
| 64 | b2, b2.length, Sub[].class); // [6] |
| 65 | } catch(Exception e) { |
| 66 | System.out.println(e); |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | /* Output: |
| 71 | a1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] |