在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)
答案 0 :(得分:7)
由于使用了@SuppressWarnings("unchecked")
,因此在编译时无法捕获该错误。删除该代码后,此语句会出现编译警告:callableList.add(new AdderImmediately(min + i, max, threadNum));
第二个问题是,您在创建AdderImmediately
类时没有使用通用形式。您显然从Set<Integer>
方法返回了call
类型。如果在您的情况下使用正确的通用形式,即Callable<Set<Integer>>
,则在上一行中问题会变得很明显。 callableList
的类型为List<Callable<Object>>
。您cannot add an element of type Callable<Set<Integer>>
into it。
由于已通过禁止一般性警告添加了错误类型的元素,因此在运行时会得到ClassCastException
。
我建议您阅读Effective Java 3rd Edition中有关泛型的章节,以更好地理解这些概念。