提出第一个问题,请理解格式错误。
在java中,使用流,可以通过使用Intstream
来用整数填充一些集合,
IntStream.range(from,to).boxed().collect(Collectors.toCollection(HashSet::new));
如果将 HashSet
替换为 ArrayList
或 LinkedList
,则只需返回指定的集合即可。
使用它,您如何设置一个方法来指定要填充的所需集合接口(interface)?我正在寻找的是这样的:
public returnType fillWithInt(Class<?> t, int from, int to){
return IntStream.range(from,to)
.boxed()
.collect(Collectors.toCollection(t::new));
}
尝试这个我收到警告:
Class(java.lang.ClassLoader)' has private access in 'java.lang.Class.
我一整天都在思考这个问题,不知道该怎么办。
我不妨说作为免责声明,我在编程方面非常陌生,所以我可能会完全错误地解决这个问题。如果是这样的话,我希望能得到正确方向的插入!
最佳答案
一个method reference无法像您尝试实现的那样使用类实例进行定义,因此您需要实现目标 Collection
的 Supplier
。
您可以使用反射来完成此操作,如下所示:
public <C extends Collection<Integer>> C fillWithInt(Class<C> t, int from, int to) {
return IntStream.range(from,to)
.boxed()
.collect(
Collectors.toCollection(
() -> {
try {
return t.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new IllegalArgumentException(e);
}
}
)
);
}
示例:
Set<Integer> set = fillWithInt(HashSet.class, 1, 10);
或者只需提供 Supplier
作为方法的参数,如下所示:
public <C extends Collection<Integer>> C fillWithInt(Supplier<C> supplier,
int from, int to){
return IntStream.range(from,to)
.boxed()
.collect(Collectors.toCollection(supplier));
}
示例:
Set<Integer> set = fillWithInt(HashSet::new, 1, 10);
关于java - 在 Java 中用整数填充任意集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40790203/