簡體   English   中英

如何在Sets.powerSet中使用通配符泛型

[英]How to use wildcard generics with Sets.powerSet

我有一些這樣的代碼

import com.google.common.collect.Sets;
public void handleInput(Set<Object> conditions){
    Set<Set<Object>> powerSet = Sets.powerSet(conditions);
    ...
}

這很好。 但我想這樣做:

public void handleInput(Set<? extends Object> conditions){
    Set<Set<? extends Object>> powerSet = Sets.powerSet(conditions);
    ...
}

因此我可以獲得作為對象子類的對象的功率集。 但這不會編譯,並且出現錯誤:

Type mismatch: cannot convert from Set<Set<capture#1-of 
? extends Object>> to Set<Set<? extends Object>>

我怎樣才能實現這個目標?

編輯:我想這與在編譯時被刪除的通用類型有關,以便編譯器無法知道powerSet不會在其創建的集合中添加非法內容。 通過將所有輸入轉換為對象並完全刪除通配符,我對客戶端進行了重新設計。 這是最好的方法嗎? 謝謝!

在這種情況下,它沒有任何意義-因為所有Java類都在某個時候擴展了java.lang.Object ? extends Object ? extends Object是多余的。

但是說到Sets.powerSet ,它就像一個魅力:

public class TestClass {

    public static class A {}

    public static class B extends A {}

    public static class C extends B {}


    public Set<? extends Set<? extends A>> exampleMethod(Set<? extends A> input) {
        return Sets.powerSet(input);
    }

    public static void main(String[] args) {
        final TestClass testClass = new TestClass();
        final A a = new A();
        final B b = new B();
        final C c = new C();

        System.out.println(
            testClass.exampleMethod(
                    ImmutableSet.of(a, b, c)
            )
        );
    }

}

如@slnowak所述,在擴展Object時,代碼確實是多余的。

但是,要了解該異常並避免它...

public void handleInput(Set<? extends Object> conditions){
    Set<? extends Set<? extends Object>> powerSet = Sets.powerSet(conditions);
    ...
}

這將進行編譯,並且更有用的是,例如,您可以使用此方法限制條件參數中的類型-您可以:

public void handleInput(Set<? extends Number> conditions){
    Set<? extends Set<? extends Number>> powerSet = Sets.powerSet(conditions);
    ...
}

這樣可以防止您傳入具有非數字類型的集合,並在編譯時警告您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM