OnJava8-Examples/arrays/ArrayCopying.java

81 lines
2.2 KiB
Java
Raw Normal View History

2016-01-25 18:05:55 -08:00
// arrays/ArrayCopying.java
// (c)2021 MindView LLC: see Copyright.txt
2016-01-25 18:05:55 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-01-25 18:05:55 -08:00
// Demonstrate Arrays.copy() and Arrays.copyOf()
import java.util.*;
import onjava.*;
import static onjava.ArrayShow.*;
class Sup { // Superclass
private int id;
2017-05-01 14:33:10 -06:00
Sup(int n) { id = n; }
@Override public String toString() {
2016-01-25 18:05:55 -08:00
return getClass().getSimpleName() + id;
}
}
class Sub extends Sup { // Subclass
2017-05-01 14:33:10 -06:00
Sub(int n) { super(n); }
2016-01-25 18:05:55 -08:00
}
public class ArrayCopying {
public static final int SZ = 15;
public static void main(String[] args) {
int[] a1 = new int[SZ];
Arrays.setAll(a1, new Count.Integer()::get);
show("a1", a1);
int[] a2 = Arrays.copyOf(a1, a1.length); // [1]
2016-01-25 18:05:55 -08:00
// Prove they are distinct arrays:
Arrays.fill(a1, 1);
show("a1", a1);
show("a2", a2);
// Create a shorter result:
a2 = Arrays.copyOf(a2, a2.length/2); // [2]
2016-01-25 18:05:55 -08:00
show("a2", a2);
// Allocate more space:
a2 = Arrays.copyOf(a2, a2.length + 5);
show("a2", a2);
// Also copies wrapped arrays:
Integer[] a3 = new Integer[SZ]; // [3]
2016-01-25 18:05:55 -08:00
Arrays.setAll(a3, new Count.Integer()::get);
Integer[] a4 = Arrays.copyOfRange(a3, 4, 12);
show("a4", a4);
Sub[] d = new Sub[SZ/2];
Arrays.setAll(d, Sub::new);
// Produce Sup[] from Sub[]:
Sup[] b =
Arrays.copyOf(d, d.length, Sup[].class); // [4]
2016-01-25 18:05:55 -08:00
show(b);
// This "downcast" works fine:
Sub[] d2 =
Arrays.copyOf(b, b.length, Sub[].class); // [5]
2016-01-25 18:05:55 -08:00
show(d2);
// Bad "downcast" compiles but throws exception:
Sup[] b2 = new Sup[SZ/2];
Arrays.setAll(b2, Sup::new);
try {
Sub[] d3 = Arrays.copyOf(
b2, b2.length, Sub[].class); // [6]
2016-01-25 18:05:55 -08:00
} catch(Exception e) {
System.out.println(e);
}
}
}
/* Output:
2016-07-22 14:45:35 -06:00
a1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
a1: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
a2: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
a2: [0, 1, 2, 3, 4, 5, 6]
a2: [0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0]
a4: [4, 5, 6, 7, 8, 9, 10, 11]
2016-01-25 18:05:55 -08:00
[Sub0, Sub1, Sub2, Sub3, Sub4, Sub5, Sub6]
[Sub0, Sub1, Sub2, Sub3, Sub4, Sub5, Sub6]
java.lang.ArrayStoreException
*/