【问题标题】:CustomList<T extends A> type mismatchCustomList<T extends A> 类型不匹配
【发布时间】:2014-06-08 01:07:02
【问题描述】:

第一个问题已解决 here,但它与另一个问题一起出现,我更喜欢创建一个新线程。

我有一个CustomList&lt;T extends A&gt;,它将与Class A1 和Class A2 一起使用,两者都扩展Class A。

我有一个Class B,其中包含CustomLists:

public Class B
{
    CustomList<A1> listA1 = new CustomList<A1>();
    public CustomList<A1> getListA1(){ return listA1;}
}

每当我尝试做时

for(A1 obj : myBClass.getListA1())
{
    /*Do something*/
}

我得到了Type mismatch : cannot convert from element type A to A1. 我没有得到它,因为getListA1() 返回一个CustomList&lt;A1&gt;。我想可能是因为CustomList&lt;T extends A&gt;。

【问题讨论】:

    标签: java android arraylist extends type-mismatch


    【解决方案1】:

    第一:

    class CustomList<T extends A> extends ArrayList<T>
    

    第二:

    class A {
        public boolean getCustomBoolean() {
            return true;
        }
    }
    

    第三:

    class A1 extends A {
    }
    

    结果:

    CustomList<A1> customList = new CustomList<A1>();
    customList.add(new A1());
    
    for (A1 obj: customList) {
        System.out.println(obj.getCustomBoolean());
    }
    

    打印:真

    【讨论】:

    • 这正是我得到的。我只需要清理项目,它现在运行良好。
    • 感谢您回答我的两个问题 ;)
    猜你喜欢
    • 1970-01-01
    • 2012-11-24
    • 2018-10-04
    • 2020-08-22
    • 2013-08-13
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    相关资源
    最近更新 更多