【发布时间】:2015-02-18 23:04:40
【问题描述】:
我正在尝试构建一个程序,将运行时间添加到特定位置。然后我将位置和时间存储在哈希图中。当我得到运行时间时,我将它添加到 LinkedList,然后尝试将新更新的 LinkedList 放在 hashmap 的 Key 值处。然而,一旦我搬到一个新的位置,运行时间不会停留在他们设计的位置,所以所有的位置最终都有相同的运行时间。我不太确定我做错了什么。感谢您的帮助。
示例数据: 位置 A:45 秒、43 秒、36 秒 位置 B:51 秒、39 秒
不正确的输出: 位置 A:39 秒、51 秒 位置 B:39 秒、51 秒
正确的输出: 位置 A:36 秒、43 秒、45 秒 位置 B:39 秒、51 秒
HashMap h = new HashMap();
LinkedList times = new LinkedList();
LinkedList newTimes = new LinkedList();
public static void addInformation(HashMap h, LinkedList times, LinkedList
newTimes) {
String location = scanner.next();
Double time = scanner.nextDouble();
if (h.containsKey(location)){
for (int i = 0; i < newTimes.size(); i++){
times.add(newTimes.get(i));
}
times.add(time);
getFastTime(times);
h.get(location).add(location, times); // cannot resolve add method
}else{
newTimes.clear();
newTimes.add(time);
getFastTime(newTimes);
h.put(location, newTimes);
}
}
public static void printInformation(HashMap h) {
Set keySet = h.keySet();
for ( Object locationName : keySet) {
//Use the key to get each value. Repeat for each key.
System.out.println("Location =" + locationName + " Time =" +
h.get(locationName));
}
}
public static void getFastTime(LinkedList times){
times.sort(null);
}
【问题讨论】:
-
虽然您当然可以自己滚动,但 Appachie Commons 和 Google 都提供了
MultiMap实现,它允许您在同一个键中存储多个值。使用其中之一可能会大大简化您的实施。请参阅此处:stackoverflow.com/questions/14925329/… 了解如何获取它们。
标签: java linked-list hashmap