HashSet<Node>
并且HashSet<NodeFunction>
不兼容,即使NodeFunction
implements/subclasses Node
。同样,也不是List<Number>
和List<Integer>
。Integer
子类Number
。
static List<Number> getNumberList(int size) {
//ArrayList<Integer> numList = null; //Doesn't compile
ArrayList<Number> numList = null; //Compiles
return numList;
}
如果编译器允许您尝试执行的操作,那么我可以执行以下操作并ClassCastException
抛出 a,这就是创建泛型的确切原因。
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main( String[] args ) {
Node nd = getInstance();
Set<Node> ndSet = nd.getNeighbour();
ndSet.add( new NodeSign() );
nd.removeSingleNeighbor(); //throws ClassCastException
}
static Node getInstance() {
return new NodeVariable();
}
}
interface Node {
public Set<Node> getNeighbour();
public void removeSingleNeighbor();
}
class NodeVariable implements Node {
Set<NodeFunction> ndFuncList = new HashSet<NodeFunction>();
public Set<NodeFunction> getNeighbour(){ return ndFuncList; } //wont' compile
//HERE!!!!
public void removeSingleNeighbor() {
NodeFunction ndFunc = (NodeFunction)ndFuncList.toArray()[ndFuncList.size()-1]; //throws ClassCastException
}
}
class NodeFunction implements Node {
public Set<NodeFunction> getNeighbour(){ return null; } //won't compile
public void removeSingleNeighbor() {}
}
class NodeSign implements Node {
public Set<NodeFunction> getNeighbour(){ return null; } //won't compile
public void removeSingleNeighbor() {}
}
一切在语义/句法上都是有效的,除了public Set<NodeFunction> getNeighbour(){}
. Java 教程涵盖了这个问题。