Reputation: 71
I'm trying to do such thing:
public class MyClass1 implements IMyInterface{
public boolean myMethod(){
...
}
}
public class MyClass2 implements IMyInterface{
public boolean myMethod(){
...
}
}
public class MyList<T extends IMyInterface> extends ArrayList<T>{
public T getSomething(){
for (int i = 0; i < size(); i++) {
if (get(i).myMethod())
return get(i);
}
return null;
}
}
So I can use it like this
public class MyClass3{
public void doSomething(MyList<IMyInterface> list){
...
}
}
public class MyClass4{
public MyList<MyClass1> list1;
public MyList<MyClass2> list2;
public MyClass4(){
MyClass3.doSomething(list1);
MyClass3.doSomething(list2);
}
}
But I getting a error with this message: The method doSomething(MyList) in the type MyClass3 is not applicable for the arguments (MyList)
Upvotes: 0
Views: 170
Reputation: 28706
This signature :
public void doSomething(MyList<IMyInterface> list)
will match as soon as the arg is a MyList
of IMyInterface
.
But in your code you try to call it with a MyList
of MyClass1
and this is not the same.
Modify the signature so that it will match all MyList
of IMyInterface
and also all MyList
of subtype of IMyInterface
. To do that you must use an upper bound widcard like this :
public void doSomething(MyList<? extends IMyInterface> list)
Upvotes: 0
Reputation: 10632
The method definition
public void doSomething(MyList<IMyInterface> list){
...
}
says that it will only accept MyList
of type IMyInterface
. You cannot pass it a MyList
of type MyClass1 or MyClass2
. MyList<MyClass1>
is a subtype of the raw type MyList
, but not of the parameterized type MyList<IMyInterface>
.
You need to use bounded wildcard type
to deal with situations like this. You need to make the parameter to accept a MyList
of type IMyInterface or some subtype of IMyInterface
. So in order to make it work, change the method parameter of doSomething
to this;
public void doSomething(MyList<? extends IMyInterface> list){
...
}
Upvotes: 1