I try something like this below, but the complier warns me for this type is not applicable for the argument… I know it’s not type safe, but any other way to do so?
public void addRow(List<? extends Car> list){
list.add( list.get(list.size()-1).getClass().newInstance() );
}
To see the problem, let’s expand the problematic method as follows:
getClass()returnsClass<? extends Car>. The compiler is not smart enough to know whether or not the wildcard (?) matchesT. The programmer can assert that the assignment is, in fact, safe:Of course, now the responsibility for type safety lies with the programmer. Don’t forget that even though it might be safe today, future code changes may invalidate the assertion.