我正在尝试创建一个接受集合类型和集合内项目类型的方法。
ArrayList<Integer> ints = getCollection(ArrayList.class, Integer.class);
如何编写 getCollection 以便在给定任何 Collection 子类和任何 Number 子类的情况下,该方法应该创建一个集合并用 Number 或数字的子类型?
最佳答案
如果可以的话,最好为集合传入一个Supplier,传入一个Function将Number转为子类型,如:
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;
}
这样,您就不需要任何转换。
更新使用流:
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));
}
关于java - 如何在给定集合名称(ArrayList、LinkedList 等)和集合中的项目的情况下创建任何集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58613584/