如何从LinkedHashMap中提取特定值以将其插入数组



任务说明我的教授希望我们使用一个哈希图和一个数组,在给定航班列表的情况下,找到从一个机场到另一个机场的最快路线。他希望我们在遍历哈希图时填充数组,找到从每个机场起飞的最快航班。我已经在链表的一个单元格中创建了包含航班目的地以及出发时间和到达时间的哈希图,但当我试图提取每个离开机场的航班的出发时间和抵达时间并将其插入数组时,我无法。有没有一种方法可以从哈希中每个单元格都有多个值的链表中提取特定值,或者我应该换一种方法?我已经确认hashmap具有正确的信息,并且运行正常。我只是无法或不知道如何访问hashmap内部的信息,将其发送到数组。调试器内部的信息看起来像

LinkedHashMap<String, LinkedList<Info>> airportsHash = new LinkedHashMap<String, LinkedList<Info>>();
LinkedList<Info> destinations;
public Info (String destination, double departureTime, double arrivalTime){
this.destination = destination;
this.departureTime = departureTime;
this.arrivalTime = arrivalTime;
}
public void fillHash(String origin, String destination, double departureTime, double arrivalTime) {
if(airportsHash.containsKey(origin)){
destinations = airportsHash.get(origin);
destinations.add(new Info(destination, departureTime/100, arrivalTime/100));
}
else{
destinations = new LinkedList<Info>();
destinations.add(new Info(destination, departureTime/100, arrivalTime/100));
airportsHash.put(origin, destinations);
}
}

首先只需要几个通用指针:

  • 当你在问题中使用"hash"一词时,你的意思实际上是"map"。使用散列是实现映射的常见方法,但它不是唯一的方法(搜索树是另一种常见技术(。最好使用结构的名称,而不是实现
  • 同样,应该使用适当的接口而不是实现类来声明变量。示例见下文
  • 记录已被引入Java。如果您使用的是最新版本的Java,那么它们是定义直接数据记录(如Info(的好方法
  • Map中有一些方法可以在不使用if语句的情况下轻松处理丢失的密钥

所以做出这些改变:

record FlightInfo(String destination, double departureTime, double arrivalTime) { }
Map<String,List<FlightInfo>> airportFlightMap = new HashMap<>();
public void addFlight(String origin, String destination, double departureTime, double arrivalTime) {
airportFlightMap
.computeIfAbsent(origin, o -> new ArrayList<>())
.add(new FlightInfo(destination, departureTime, arrivalTime));
}

最好是有一个包含航班的Airport类,但这超出了你的问题范围。

当我试图提取每个航班的出发和到达时间时离开机场的航班把它们插入阵列中,我做不到。是有一种方法可以从链接列表中提取特定值哈希中的每个单元格中都有多个值,还是应该继续换一种方式?

从字面上理解你的问题,提取每个离开机场的航班的起飞和到达时间的方法是:

List<Double> departureTimes = airportFlightMap.get(airportName)
.stream().map(FlightInfo::departureTime).collect(Collectors.toList());
List<Double> arrivalTimes = airportFlightMap.get(airportName)
.stream().map(FlightInfo::arrivalTime).collect(Collectors.toList());

尽管我不确定这是如何让你更接近找到从一个机场到另一个机场的最快路径的目标的。为此,您需要一个搜索算法。例如,在伪代码中

find path(current route, destination):
if end of current route = destination:
process path
else
for each flight from end of current route:
if next airport not in current route:
find path(current route + next airport, destination)

在该算法中,您可能希望存储原点和FlightInfo的列表作为当前路线。这样你就可以很容易地比较到达时间,找到最佳路线。

最新更新