如何使用<>从类中引用方法并传递变量

时间:2019-05-02 10:35:23

标签: java

我正在尝试从类

引用方法shortestPathBetween(N from, N to)
public class DijkstraGraphAnalyzer<N extends Node<N, E>, E extends Edge<N, E>> implements GraphAnalyzer<N, E>
在类MainMenuController

传递变量,以便该方法可以在从选择框派生的输入上运行。

我尝试创建该类的局部变量,但随后它希望我将完全相同的参数<N, E>添加到MainMenuController

MainMenuController.java

public <MapPoint> List<MapPoint> shortestPathBetween(MapPoint from, MapPoint to) {
  from = (MapPoint) MainMenuController.source;
  to = (MapPoint) MainMenuController.target;
  List<MapPoint> shortestPathBetween = dga.shortestPathBetween(from, to);
  shortestPathBetween = shortestPathBetween(from, to);

  System.out.println("Source : \n" + from + " Target : \n" + to);

  return shortestPathBetween;
}

DijsktraGraphAnalyzer.java

public class DijkstraGraphAnalyzer<N extends Node<N, E>, E extends Edge<N, E>> implements GraphAnalyzer<N, E> {

    private final Graph<N, E> graph;
    // Store the default node/distance mapping for efficiency.
    private final Map<N, Double> defaultNodeDistanceMapping;
    private final Map<N, N> defaultPreviousNodeMapping;

    public DijkstraGraphAnalyzer(final Graph<N, E> graph) {
        this.graph = graph;
        this.defaultNodeDistanceMapping = new HashMap<N, Double>();
        this.defaultPreviousNodeMapping = new HashMap<N, N>();
        for (final N n : this.graph.getNodes()) {
            this.defaultNodeDistanceMapping.put(n, Double.MAX_VALUE);
            this.defaultPreviousNodeMapping.put(n, null);
        }
    }

    @Override
    public List<N> shortestPathBetween(N from, N to) {
        final Map<N, Double> nodeDistanceMapping = buildNodeDistanceMapping(from);
        final Map<N, N> previousNodeMapping = new HashMap<N, N>(defaultPreviousNodeMapping);

        final Set<N> unsettled = new HashSet<N>();
        unsettled.add(from); 
.......

理想情况下,我希望能够将两个MapPoints传递给该方法,以便它可以在各自的类中运行。

1 个答案:

答案 0 :(得分:1)

这里:

public <MapPoint> List<MapPoint> shortestPathBetween(MapPoint from, MapPoint to)

没有任何意义。如果MapPoint已经是一个现有的类,则签名不需要任何泛型:

public List<MapPoint> shortestPathBetween(MapPoint from, MapPoint to)

如果MapPoint实际上是一个类型参数,则最好按照约定命名,例如

public <T> List<T> shortestPathBetween(T from, T to)

除此之外,我建议您重新考虑如何在Java中使用泛型,正式的tutorial是一个很好的起点。