gpt4 book ai didi

java - 如何使用<>引用类中的方法并传入变量

转载 作者:行者123 更新时间:2023-12-02 09:56:42 39 4
gpt4 key购买 nike

我正在尝试引用方法shortestPathBetween(N from, N to)来自类(class)

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

在类(class)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);
.......

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

最佳答案

这里:

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是一个很好的起点。

关于java - 如何使用<>引用类中的方法并传入变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55950566/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com