Java中的范型类型强制转化注意

class Person {
	
}

class Student extends Person {
	
}

public class Test {
	public static void main(String[] args) {
		ArrayList list = new ArrayList();
	}
}

错误提示:Type mismatch: cannot convert from ArrayList to ArrayList

这里觉得很奇怪为什么不能使用呢?因为这里Person确实是Student的子类。


http://stackoverflow.com/questions/23199874/convert-arraylistsubclass-to-arraylistsuperclass


The fundamental issue you are facing is that List is not a subtype of List.

The way to solve your problem is to declare the variable using a generic bound:

List search;

then this will compile:

search = foods;

The declaration List means "A List of an unknown type that is a subtype of Organism". In code, elements of such a list are known to at least be an Organism, but the exact type is unknown.



你可能感兴趣的:(java的泛型)