我的vertex interface
包含element
public interface Vertex<V> {
public V element()throws InvalidEdgeException;
}
implementation
interface vertices
的{{1}}
class MyVertices
我的疑问是,当我尝试测试方法时public class MyVertex<V,E> implements Vertex<V> {
private V elem;
private Graph<V, E> myGraph;
public MyVertex(V elem) {
this.elem = elem;
this.myGraph = new GraphLinked<>();
}
@Override
public V element() throws InvalidVertexException {
if (elem == null) {
throw new InvalidVertexException("vertex null");
}
return elem;
}
private MyVertex checkVertex(Vertex<V> p) throws InvalidVertexException {
if (p == null) {
throw new InvalidVertexException("checkVertex = NULL");
}
try {
return (MyVertex) p;
} catch (ClassCastException e) {
throw new InvalidVertexException("WRONG vertex");
}
}
}
返回checkVertex(Vertex<V> p)
,因为throw new InvalidVertexException("WRONG vertex")
不能cast
MyVertex
制作接口的实现,当然应该做一个转换,因为它实现了它的接口
任何建议?
答案 0 :(得分:1)
删除虚拟try-catch ClassCastException
,您将知道投射失败的原因。