I have outer generic class which has some inner class, for which I’d like to use the generic type of outer class.
However, I don’t understand how to use generic parameters correctly.
Example:
class Outer<E extends CharSequence>{
class Inner extends ArrayList<E>{
}
void func() {
ArrayList<CharSequence> al = new ArrayList<CharSequence>();
al.add("abc"); // OK
CharSequence a = al.get(0); // OK
Inner in = new Inner();
in.add("abc"); // Error: The method add(E) in the type ArrayList<E> is not applicable for the arguments (String)
CharSequence b = in.get(0); // OK
}
}
How can I declare inner class to use same generic type of outer class?
Thanks
EDIT + Solution:
Finally I achieved what I wanted, here’s example result:
abstract class MyGenericClass<E extends CharSequence>{
class TheList extends ArrayList<E>{};
TheList list = new TheList();
}
final class ClassInstance extends MyGenericClass<String>{
};
public class Main{
public static void main(String[] args){
ClassInstance c = new ClassInstance();
c.list.add("abc");
String s = c.list.get(0);
}
}
My requirement was to have generic class, and also have generic container in it, which would use same type parameter as its parent class.
Note: CharSequence/String are example parameters of use, my real usage is different.
Inneris already using the same generic type asOuter. The problem is thatfuncis not using it, it is usingCharSequence.As SLaks explained
funcwill do funky stuff in all cases except when it is called on anOuter<CharSequence>: e.g. when called onOuter<String>it will add aCharSequenceto anArrayList<String>.Now, if
funcalready had an object of that concrete type:It would do the right thing. So the compiler allows this.
It seems you tried to create a generic question from some specific issue you are facing. If you described what you are trying to do and failing you will have better chance of resolving it here.