[英]How to add List<Future<Object>> into Set<Object>?
在ExecutorService的开发过程中,有必要将List放入Set中。 如何才能做到这一点?
public class Executor {
private Set<List<Future<Object>>> primeNumList = Collections.synchronizedSet(new TreeSet<>());
Set<List<Future<Object>>> getPrimeNumList() {
return primeNumList;
}
@SuppressWarnings("unchecked")
public void setup(int min, int max, int threadNum) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
List<Callable<Object>> callableList = new ArrayList<>();
for (int i = 0; i < threadNum; i++) {
callableList.add(new AdderImmediately(min + i, max, threadNum));
}
List<Future<Object>> a = executorService.invokeAll(callableList);
primeNumList.add(a); // here i try to add Future list into Set
System.out.println(primeNumList);
executorService.shutdown();
}
我的类我处理值并通过call()返回它们。 之后,他们会从我希望将它们放入最终Set中的列表中进入列表
public class AdderImmediately implements Callable {
private int minRange;
private int maxRange;
private Set<Integer> primeNumberList = new TreeSet<>();
private int step;
AdderImmediately(int minRange, int maxRange, int step) {
this.minRange = minRange;
this.maxRange = maxRange;
this.step = step;
}
@Override
public Object call() {
fillPrimeNumberList(primeNumberList);
return primeNumberList;
}
private void fillPrimeNumberList(Set<Integer> primeNumberList) {
for (int i = minRange; i <= maxRange; i += step) {
if (PrimeChecker.isPrimeNumber(i)) {
primeNumberList.add(i);
}
}
}
}
是否有可能实施? 因为我现在拥有的,我得到一个ClassCastException。 或者我不明白什么?)
例外:
Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(TreeMap.java:1294)
at java.util.TreeMap.put(TreeMap.java:538)
at java.util.TreeSet.add(TreeSet.java:255)
at java.util.Collections$SynchronizedCollection.add(Collections.java:2035)
at Executor.setup(Executor.java:22)
at Demo.main(Demo.java:47)
您无法在编译时捕获错误,因为您已使用@SuppressWarnings("unchecked")
。 删除它时,在此语句中有一个编译警告: callableList.add(new AdderImmediately(min + i, max, threadNum));
第二个问题是,在创建AdderImmediately
类时,您没有使用泛型表单。 您正在返回,从call
方法Set<Integer>
类型。 如果在您的情况下使用正确的通用形式,即Callable<Set<Integer>>
,则问题在上面的行中变得清晰。 callableList
的类型是List<Callable<Object>>
。 您不能在其中添加Callable<Set<Integer>>
类型的元素 。
因为您通过抑制一般警告添加了不正确类型的元素,所以您在运行时获得ClassCastException
。
我建议你阅读Effective Java 3rd Edition中关于Generics的章节,以便更好地理解这些概念。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.