どのようにリスト<今後の<Object >>セット<オブジェクト>に追加するには?

VIRICH:

ExecutorServiceのの開発中に、それがセットにリストを置くことが必要となりました。これはどのように行うことができますか?

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();
    }

私は値を処理し、呼び出しを介してそれらを返すている私のクラス()。彼らは私が彼らが最終セットに配置する場所からリストに陥るその後

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)
curlyBraces:

あなたが使用しているので、コンパイル時にエラーをキャッチすることができません@SuppressWarnings("unchecked")それを削除するには、この文では、コンパイル警告があります:callableList.add(new AdderImmediately(min + i, max, threadNum));

第二の問題は、作成時に一般的な形式を使用していない、あるAdderImmediatelyクラスを。あなたは明確に、戻ってきているSet<Integer>からタイプをcallする方法。あなたの場合には、適切な一般的な形式を使用している場合、すなわち、Callable<Set<Integer>>問題は上記の行で明らかになりました。種類callableListIS List<Callable<Object>>あなたはタイプの要素を追加することはできませんCallable<Set<Integer>>それに

あなたは一般的な警告を抑制することにより、間違った型の要素を追加したので、あなたが取得しているClassCastException、実行時に。

私はより良いこれらの概念を理解するために効果的なJavaの第3版からジェネリック医薬品の章を読むことをおお勧めします。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=199546&siteId=1