sorry I know similar questions have been asked before, but none of them solve my current problem.
I currently have something like this:
abstract class MyAbstractParameter{ /* Some methods/parameters */ }
class MyParameter extends MyAbstractParameter { /*more methods/parameters*/ }
abstract class MyAbstractClass<T extends MyAbstractParameter> extends Thread{
private List<MyAbstractParameter> list;
public MyAbstractClass(List<MyAbstractParameter> list) { this.list = list; }
public List<MyAbstractParameter> getList() { return list; }
public void run() {
for(MyAbstractParameter e : list) {
doStuffWithList((T) e); // WARNING IS HERE WHEN CASTING! ! !!
}
}
public abstract void doStuff(T element);
}
class MyClass extends MyAbstractClass<MyParameter> {
public MyClass(List<MyAbstractParameter> list) { super(list); }
public void doStuff(MyParameter element) { /* does something */ }
}
I want that the method getList()
to always returns a List<MyAbstractParameter>
, and it does, however it gives me this warning, and I understand that the reason behind it is that if I send a list of MyOtherParameter extends MyAbstractParameter
, the cast would fail, and I will cry.
So I decided to go for private List<? extends MyAbstractParameter> list;
private List<? extends MyAbstractParameter> list;
, but I had to the modify everything so that there is no problem with this <? ...>
<? ...>
.
So... Is there another way if doing it, while avoiding to modify everything?
I mean.. like doing something in MyAbstractClass
, without using @SuppressWarning("unchecked")
.
If every element in the list is supposed to be a an instance of T, then the list should be a List<T>
:
abstract class MyAbstractClass<T extends MyAbstractParameter> extends Thread {
private List<T> list;
public MyAbstractClass(List<T> list) { this.list = list; }
public List<T> getList() { return list; }
public void run() {
for (T e : list) {
doStuffWithList(e);
}
}
public abstract void doStuff(T element);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.