簡體   English   中英

將子類添加到列表-方法add(capture#2-of擴展TopBean)…不適用於自變量(TopBean)

[英]Adding subclass to list - The method add(capture#2-of ? extends TopBean)…not applicable for the arguments (TopBean)

我之前曾問過這個問題,但從未找到解決方法。

我試圖將一個子類型添加到定義如下的列表中。 這應該是100%合法的,子類型擴展了主要類型。

private List<? extends TopBean> beans;

public List<? extends TopBean> getBeans() {
        return beans;
}

我正在嘗試這樣做:

this.getBeans().add(new SecondaryBean());

SecondaryBean擴展了TopBean (不是直接擴展,而是在某種程度上)。

這讓我發瘋-錯誤是

The method add(capture#2-of ? extends TopBean) in the type List<capture#2-of ? extends TopBean> is not applicable for the arguments (SecondaryBean)

如果我將其轉換為TopBean,則出現相同的錯誤,只是措辭不同

he method add(capture#2-of ? extends TopBean) in the type List<capture#2-of ? extends TopBean> is not applicable for the arguments (TopBean) he method add(capture#2-of ? extends TopBean) in the type List<capture#2-of ? extends TopBean> is not applicable for the arguments (TopBean)

必須在通用TopBeans列表中添加一個子SecondaryBean。 在這里做什么?

您不能向以這種方式定義的通配符添加任何非空值。

如果您已經定義了

List<? super TopBean>

然后可以添加任何擴展TopBean的內容,但要換個故事-只有TopBean擴展或實現的內容

我不明白為什么首先將列表定義為通配符,將其定義為List似乎可以為您提供所需的一切。 有時應使用wikdcards定義方法,但不應使用數據成員定義

基本上,您的聲明是錯誤的。 不要在變量聲明或返回類型中使用通配符。 僅將通配符用於方法參數。

private List<TopBean> beans;

public List<TopBean> getBeans() {
        return beans;
}

為什么可能有很多原因和討論,為什么除了方法參數之外,您什么地方都不使用通配符,但這是我個人的一般規則。 它過於簡單,但是將覆蓋Java中所有泛型使用的90%-99%。

現在,使用上面給出的代碼,您可以將TopBean或TopBean的任何子類添加到列表中。

我解決了這個問題。 使用下面的強制轉換,錯誤消失了(有一個警告,但我可以接受)。

((List<SecondaryBean>)this.getBeans()).add(new SecondaryBean());

我保證有一個SecondaryBeans列表,所以這很安全。

暫無
暫無

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

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