我正在尝试构建一个程序,将运行时间添加到特定位置。然后,我将位置和时间存储在哈希图中。得到运行时间后,将其添加到LinkedList,然后尝试将新更新的LinkedList放在哈希图的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通过引用传递。您没有为不同的位置创建新列表,因此同一列表用于地图中的所有条目。您应该对此进行阅读,因为它是Java的基本方面。

接下来,应该对您的集合进行参数化。您不需要时间和newTimes列表。在地图中也使用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 - 如何在现有键处将唯一值添加到哈希图,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28595671/

10-11 23:10
查看更多