2015-09-07 11:44:36 -06:00
|
|
|
// generics/PrimitiveGenericTest.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-11-11 20:20:04 -08:00
|
|
|
import onjava.*;
|
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:
|
|
|
|
class FArray {
|
2015-11-03 12:00:44 -08:00
|
|
|
public static <T> T[] fill(T[] a, Supplier<T> gen) {
|
2015-06-15 17:47:35 -07:00
|
|
|
for(int i = 0; i < a.length; i++)
|
2015-11-03 12:00:44 -08:00
|
|
|
a[i] = gen.get();
|
2015-06-15 17:47:35 -07:00
|
|
|
return a;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public class PrimitiveGenericTest {
|
|
|
|
public static void main(String[] args) {
|
|
|
|
String[] strings = FArray.fill(
|
2015-11-03 12:00:44 -08:00
|
|
|
new String[7], new RandomSupplier.String(10));
|
2015-06-15 17:47:35 -07:00
|
|
|
for(String s : strings)
|
|
|
|
System.out.println(s);
|
|
|
|
Integer[] integers = FArray.fill(
|
2015-11-03 12:00:44 -08:00
|
|
|
new Integer[7], new RandomSupplier.Integer());
|
2015-06-15 17:47:35 -07:00
|
|
|
for(int i: integers)
|
|
|
|
System.out.println(i);
|
|
|
|
// Autoboxing won't save you here. This won't compile:
|
|
|
|
// int[] b =
|
2015-11-03 12:00:44 -08:00
|
|
|
// FArray.fill(new int[7], new RandIntSupplier());
|
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
|
|
|
YNzbrnyGcF
|
|
|
|
OWZnTcQrGs
|
|
|
|
eGZMmJMRoE
|
|
|
|
suEcUOneOE
|
|
|
|
dLsmwHLGEa
|
|
|
|
hKcxrEqUCB
|
|
|
|
bkInaMesbt
|
|
|
|
7052
|
|
|
|
6665
|
|
|
|
2654
|
|
|
|
3909
|
|
|
|
5202
|
|
|
|
2209
|
|
|
|
5458
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|