I am trying to create a method that accepts the type of collection and the type of items inside the collection.
ArrayList<Integer> ints = getCollection(ArrayList.class, Integer.class);
How do I write the getCollection so that, given any Collection subclass and any Number subclass, the method should create a collection and populate it with random elements of Number or subtype of Number?
If you can, it would be better to pass in a Supplier for the collection, and a Function to convert from Number to the sub-type, such as:
private static final SecureRandom RND = new SecureRandom();
private static final int COUNT_MAX = 100;
public static void main(String[] args) {
ArrayList<Integer> ints = getCollection(ArrayList::new, Number::intValue);
System.out.println(ints);
Set<Double> doubles = getCollection(HashSet::new, Number::doubleValue);
System.out.println(doubles);
}
private static <T extends Collection<U>, U extends Number> T getCollection(
Supplier<T> supplier, Function<Number, U> fn) {
T collection = supplier.get();
int count = RND.nextInt(COUNT_MAX);
for (int i = 0; i < count; i++)
collection.add(fn.apply(RND.nextInt()));
return collection;
}
This way, you won't need any casting.
Update using streams:
private static <T extends Collection<U>, U extends Number> T getCollection(
Supplier<T> supplier, Function<Number, U> fn) {
int count = RND.nextInt(COUNT_MAX);
return RND.ints().limit(count).boxed().map(fn)
.collect(Collectors.toCollection(supplier));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.