在 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 中的位置落入 Listpublic 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。还是我不明白什么?)
1 回答
手掌心
TA贡献1942条经验 获得超3个赞
您无法在编译时捕获错误,因为您使用了@SuppressWarnings("unchecked")
. 在删除它时,此语句中有一个编译警告:callableList.add(new AdderImmediately(min + i, max, threadNum));
第二个问题是,您在创建AdderImmediately
类时没有使用通用形式。您显然是在返回,Set<Integer>
从call
方法中输入。如果在您的情况下使用正确的通用形式,即 ,Callable<Set<Integer>>
问题在上面的行中变得清晰。的类型callableList
是List<Callable<Object>>
。您不能添加类型的元素Callable<Set<Integer>>
进去。
因为您通过抑制一般警告添加了不正确类型的元素,所以您ClassCastException
在运行时得到了。
我建议您阅读 Effective Java 3rd edition 中关于泛型的章节,以更好地理解这些概念。
添加回答
举报
0/150
提交
取消