2012-11-21 92 views
-1

嗨,大家好,我遇到了一個不安全的投射操作問題。 這是問題所在。我得到構造函數接受不同類型的訂單(PlayList,UserOperations等)或應該。所以我決定給它一個參數作爲對象,並檢查一次被調用的接收類型。問題是其中之一是參數化ArrayList(ArrayList < PlayList>),因爲它是不可能檢查參數化的ArrayList我必須「挖」英寸在第一步我檢查它是否是一個ArrayList,在第二個我進入它檢查其內容的類型。 之後的問題是我得到一個不安全的警告,我不知道如何處理。不安全的參數化ArrayList在執行檢查後投射

問候

public Order(int aTyp, Object aOrderContent) { 
    this.orderTyp = aTyp; 
    if (aOrderContent instanceof ArrayList<?>) { 
     ArrayList<?> objList = (ArrayList<?>)aOrderContent; 
    if (objList.get(0) != null && (objList.get(0)) instanceof PlayList) { 
     playList.addAll((ArrayList<PlayList>)aOrderContent) ; 
    }   

    } else if (aOrderContent instanceof UserOP) { 

    } 
} 

回答

0

不是使構造函數接受一個Object超載你的構造函數。有一個採取List<?>和一個採取UserOP等。另外,如果List的所有選項都從同一接口擴展,那麼這將是理想選擇,因此您可以使用List<MyInterface>而不是List<?>

2

重新考慮您的設計。不要讓構造函數採取Object。這太不透明,並允許您的代碼的消費者通過任何類型。這聽起來像你應該using a generic class而不是(根據你的部分例子很難說)。可能的解決方法:

// Might need an upper bound on T if you want to limit the allowed parameterizations 
class Order<T> { 

    private final int orderTyp; 
    private final List<T> someList = new ArrayList<>(); 

    public Order(int aTyp, List<t> aOrderContent) { 
     this.orderTyp = aTyp; 
     someList.addAll(aOrderContent); 
    } 
} 

請記住它可能會更好,而不是use an enumint的爲orderTyp,如果你知道(在編譯時)所有可能的類型值。


附註:如果List是空的,List#get(0) with throw an exception,不會返回null

相關問題