Domanda

First problem fixed here but it came with another one, and I prefered to make a new thread.

I have a CustomList<T extends A> which will be used with Class A1 and Class A2, both extending Class A.

I have a Class B which contains CustomLists :

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

Whenever I try to do

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

I got Type mismatch : cannot convert from element type A to A1. I don't get it since getListA1() returns a CustomList<A1>. I think it may be because of CustomList<T extends A>.

È stato utile?

Soluzione

First:

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

Second:

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

Third:

class A1 extends A {
}

Result:

CustomList<A1> customList = new CustomList<A1>();
customList.add(new A1());

for (A1 obj: customList) {
    System.out.println(obj.getCustomBoolean());
}

Prints: true

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top