2015-09-07 11:44:36 -06:00
|
|
|
// generics/PrimitiveGenericTest.java
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 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.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2015-11-11 20:20:04 -08:00
|
|
|
import onjava.*;
|
2016-01-25 18:05:55 -08:00
|
|
|
import java.util.*;
|
2015-11-03 12:00:44 -08:00
|
|
|
import java.util.function.*;
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
// Fill an array using a generator:
|
2016-01-25 18:05:55 -08:00
|
|
|
interface FillArray {
|
|
|
|
static <T> T[] fill(T[] a, Supplier<T> gen) {
|
2017-01-20 21:30:44 -08:00
|
|
|
Arrays.setAll(a, n -> gen.get());
|
2015-06-15 17:47:35 -07:00
|
|
|
return a;
|
|
|
|
}
|
2016-01-25 18:05:55 -08:00
|
|
|
static int[] fill(int[] a, IntSupplier gen) {
|
2017-01-20 21:30:44 -08:00
|
|
|
Arrays.setAll(a, n -> gen.getAsInt());
|
2016-01-25 18:05:55 -08:00
|
|
|
return a;
|
|
|
|
}
|
|
|
|
static long[] fill(long[] a, LongSupplier gen) {
|
2017-01-20 21:30:44 -08:00
|
|
|
Arrays.setAll(a, n -> gen.getAsLong());
|
2016-01-25 18:05:55 -08:00
|
|
|
return a;
|
|
|
|
}
|
|
|
|
static double[] fill(double[] a, DoubleSupplier gen) {
|
2017-01-20 21:30:44 -08:00
|
|
|
Arrays.setAll(a, n -> gen.getAsDouble());
|
2016-01-25 18:05:55 -08:00
|
|
|
return a;
|
|
|
|
}
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
public class PrimitiveGenericTest {
|
|
|
|
public static void main(String[] args) {
|
2016-01-25 18:05:55 -08:00
|
|
|
String[] strings = FillArray.fill(
|
|
|
|
new String[5], new Rand.String(9));
|
|
|
|
System.out.println(Arrays.toString(strings));
|
|
|
|
int[] integers = FillArray.fill(
|
2016-11-21 12:37:57 -08:00
|
|
|
new int[9], new Rand.Pint());
|
2016-01-25 18:05:55 -08:00
|
|
|
System.out.println(Arrays.toString(integers));
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2016-07-22 14:45:35 -06:00
|
|
|
[btpenpccu, xszgvgmei, nneeloztd, vewcippcy, gpoalkljl]
|
|
|
|
[635, 8737, 3941, 4720, 6177, 8479, 6656, 3768, 4948]
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|