我正在尝试构建一个程序,将运行时间添加到特定位置。然后我将位置和时间存储在 HashMap 中。当我获得运行时间时,我将其添加到 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);
}
最佳答案
问题在于 Java 通过引用传递。您不会为不同位置创建新列表,因此同一列表将用于 map 中的所有条目。您应该阅读本文,因为它是 Java 的一个基本方面。
接下来,您的集合应该被参数化。您不需要 times 和 newTimes 列表。在 map 中也使用 List 而不是 LinkedList。像这样:
HashMap<String, List<Double>> map = new HashMap<>();
并在方法定义中执行相同的操作。还有许多其他问题,例如 printInformation 方法假设对象是字符串,甚至没有对它们进行转换。输入未经验证。如果输入格式错误怎么办?应该考虑这一点。另外,变量的命名应该更好。
这样的东西应该可以工作(未经测试。您还必须查看 print 方法以使其与列表一起使用):
HashMap<String, List<Double>> map = new HashMap<>();
public static void addInformation(HashMap<String, List<Double>> map) {
//input should be validated here
String location = scanner.next();
Double time = scanner.nextDouble();
List<Double> timesInMap = map.get(location);
if (timesInMap != null){
timesInMap.add(time);
timesInMap.sort(null);
}else{
timesInMap = new ArrayList<Double>();
timesInMap.add(time);
map.put(location, timesInMap);
}
}
public static void printInformation(HashMap<String, List<Double>> map) {
Set<String> keySet = map.keySet();
for (String locationName : keySet) {
//Use the key to get each value. Repeat for each key.
System.out.println("Location =" + locationName + " Time =" +
map.get(locationName));
}
}
关于java - 如何在现有键处将唯一值添加到 HashMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28595671/