I’ve two classes that use generic types (A, B).
My question is – What is the best way to work with the first generic type (TA) from inside B ?
Here is simplified example:
public class A<TListItemsType>
{
List<TListItemsType> list = new LinkedList<TListItemsType>();
public List<TListItemsType> getList()
{
return list;
}
}
public class B<TContainderType extends A>
{
TContainderType temp = null;
public B(TContainderType cont)
{
temp=cont;
}
public void DoWork()
{
for (TListItemsType item : temp.getList())
{
System.out.println(item);
}
}
}
I’ve tried the solution suggested here –
public class B<TContainderType extends A<TListItemsType>>
{
TContainderType temp = null;
public B(TContainderType cont)
{
temp=cont;
}
public void DoWork()
{
for (TListItemsType item : temp.getList())
{
System.out.println(item);
}
}
}
And it works as long as use pre defined type such as Integer or String, sadly, this doesn’t work as the compiler doesn’t recognize the generic as class name.
So went further on and tried to configure another generic type and then use it inside the extends:
public class B<TListItemsType, TContainderType extends A<TListItemsType>>
{
TContainderType temp = null;
public B(TContainderType cont)
{
temp=cont;
}
public void DoWork()
{
for (TListItemsType item : temp.getList())
{
System.out.println(item);
}
}
}
And it actually works, but it doesn’t smell right. Is there another way to use generic type used n another generic type?
The way you did it using
B<TListItemsType, TContainderType extends A<TListItemsType>>looks good to me…The reason this makes sense is that your
Bclass now indeed needs two parameters to describe it:TListItemsTypeandTContainderType. In fact, you are even usingTListItemsTypeexplicitly in yourDoWork()function insideB. So it’s only fair that you need to pass it as a parameter. Otherwise the compiler wouldn’t even know what you mean inside yourDoWork()function, as you could just as well write the class definition like this:(Notice that I a renamed the type entirely, but just in
B, not inA!)If it simply required you to use the same name
TListItemsTypeas used in the definition ofA, you would be quite limited in the things you could do with generics. For example, you could not accept one type extendsList<E>and another extendsEnum<E>, since both of these used<E>as their generic identifier.I hope it smells better now… 🙂