我正在尝试创建一个泛型类,其中泛型类型本身可以有方法。
这就是我在Java中所做的:
public class DepthFirstPaths <GraphType> implements PathInterface
{
private final int start;
public DepthFirstPaths (GraphType G, int s)
{
int vCount = G.numVertex(); //This line is giving errors
start = s;
DFS(G, s);
}
//Other methods
....
}
GraphType可以引用有向图类型或无向图类型,这是因为DFS对给定源顶点的两种类型的图形执行相同的操作。但是上面的java代码给出了如下错误:
Description: The method numVertex() is undefined for the type GraphType
Resource: DepthFirstPaths.java
Path: /Paths/src/GraphAlgorithms
Location: line 17
Type: Java Problem
加上与在代码中使用GraphType object
方法相关的其他错误
我该怎么做才能解决这个问题?这样做的最佳方式是什么?
答案 0 :(得分:4)
这个定义
public class DepthFirstPaths <GraphType>
表示您的通用类型名称为GraphType
。
要让您的课程始终使用GraphType
,您应该在GraphType
标记您的通用扩展名:
public class DepthFirstPaths <T extends GraphType>
然后在代码中使用T
来引用通用:
public class DepthFirstPaths <T extends GraphType> implements PathInterface {
private final int start;
public DepthFirstPaths (T G, int s) {
//This line won't give you errors anymore
//except if GraphType doesn't have a numVertex method
int vCount = G.numVertex();
start = s;
DFS(G, s);
}
//Other methods
....
}