Reputation: 524
I searched stack overflow for this error, but none quite had the same design as I have. Suggestions for terminology to aid in finding a similar topic like the sample code below would be appreciated.
Here is a simple test case that demonstrates the error:
import java.util.List;
public class SimpleTest {
abstract class AbsTask<T>
{
}
abstract class AbsQueue<T extends AbsTask<?>>
{
private List<T> lst;
public void addSpecialItem()
{
lst.add(new SpecialItem()); // Error occurs here
}
}
class SpecialItem extends AbsTask<Void>
{
}
}
I am trying to add a method to my abstract class AbsQueue
called addSpecialItem
, which will insert the SpecialItem class into the list generic list T which is essentially a list of AbsTask
.
Here is the error: The method add(T) in the type List<T> is not applicable for the arguments (SimpleTest.SpecialItem)
I can resolve this error if I type case the add line as follows:
lst.add((T)new SpecialItem());
Is there a way of handling this without type casting new SpecialItem()
to T
?
Upvotes: 2
Views: 10951
Reputation: 39225
Your abstract class must be instantiated to define what T is. Try this:
public class SimpleTest {
static abstract class AbsTask<T> { }
static class AbsQueue<T extends AbsTask<?>> {
private List<T> lst;
public void addSpecialItem(T item) {
lst.add(item);
}
}
static class Test {
public void main() {
AbsQueue<SpecialItem> queue = new AbsQueue<SpecialItem>();
queue.addSpecialItem(new SpecialItem());
}
}
static class SpecialItem extends AbsTask<String> {
}
}
Upvotes: 2
Reputation: 9781
At that line of code lst.add(new SpecialItem());
the compiler does not yet know what T
is.
Upvotes: 0
Reputation: 198023
A List<T>
is supposed to be a list that can only include elements of type T
, but the code you've written doesn't ensure that SpecialItem
is a subtype of T
.
It's not clear what you actually want, but I think what you want is a List<AbsTask<?>>
, not a List<T>
for some specific T
that extends AbsTask<?>
.
Upvotes: 0