我有一个类GraphSearch,其定义如下:
public class GraphSearch{
///code
}
此类是泛型参数化方法:
public static <T> int dsp(T start, Map<T, List<Pair<T, Integer>>> adjList, T goal) {
///code}
我有一个主要的工具,我会进行此设置并按如下方式调用方法:
GraphSearch g = new GraphSearch();
HashMap<String,ArrayList<Pair<String,Integer>>> k = new HashMap<String, ArrayList<Pair<String, Integer>>>();
////various setup to fill my map with valid stuff
///Pair is a class I made in my package
然后主要是
System.out.println("dsp from A to E is" + g.dsp("a", k, "e"));
我得到一个错误。
The method dsp(T, Map<T,List<Pair<T,Integer>>>, T) in the type GraphSearch is not applicable for the arguments (String, HashMap<String,ArrayList<Pair<String,Integer>>>, String)
好吧,为什么不呢?ArrayList不是列表吗?字符串不是通用类型吗?哈希图不是地图吗?
这是怎么回事?
这里的问题很细微,但这是基于这样的事实,即在Java泛型中,即使不是extend ,aType<A>
也不是aType<B>
A
B
。在这里,A
是ArrayList
和B
是List
。
您定义了一个HashMap<String,ArrayList<Pair<String,Integer>>>
,但是您的方法需要一个Map<String,List<Pair<String,Integer>>>
。尝试定义k
withList
而不是ArrayList
,它应该可以工作:
HashMap<String,List<Pair<String,Integer>>> k =
new HashMap<String, List<Pair<String, Integer>>>();
或定义要使用的dsp
方法ArrayList
:
public static <T> int dsp(T start, Map<T, ArrayList<Pair<T, Integer>>> adjList, T goal) {
此外,即使允许,您也应该dsp
通过类的实例访问静态方法。为了清楚起见,最好使用类名来访问它:
// GraphSearch.dsp instead of g.dsp.
System.out.println("dsp from A to E is" + GraphSearch.dsp("a", k, "e"));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句