如何将List <Future <Object >>添加到Set <Object>?

VIR*_*ICH 3 java multithreading

在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();
    }
Run Code Online (Sandbox Code Playgroud)

我的类我处理值并通过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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

是否有可能实施?因为我现在拥有的,我得到一个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)
Run Code Online (Sandbox Code Playgroud)

cur*_*ces 7

您无法在编译时捕获错误,因为您已经使用过@SuppressWarnings("unchecked").删除它后,在此语句中有一个编译警告:callableList.add(new AdderImmediately(min + i, max, threadNum));

第二个问题是,在创建AdderImmediately类时没有使用泛型表单.您正在返回,Set<Integer>call方法中键入.如果在您的情况下使用正确的通用形式,即,Callable<Set<Integer>>问题在上面的行中变得清晰.类型callableListList<Callable<Object>>.您不能添加类型的元素Callable<Set<Integer>>进去.

因为您通过抑制一般警告添加了不正确类型的元素,所以您将ClassCastException在运行时获得.

我建议你阅读Effective Java 3rd Edition中关于Generics的章节,以便更好地理解这些概念.