0

我正在从一个文件中解析,其中我有城市名称和到其他城市的距离,格式如下:

"San Antonio" 
"San Francisco" 
Washington 

"San Francisco"--Weed [305]
"San Francisco"--"Wisconsin Dells" [2189]
Washington--"San Jose" [2909]

我认为问题在于,当我切碎字符串时,它会创建不同的对象,并且由于某种原因, String.equals 和/或 hashcode() 会给出不同的结果。因此, Map.get(key) 返回空值。然而,我不知道如何解决这个问题。

public class spanning {
private static HashMap<String, HashMap<String, Integer>> map = new HashMap<String, HashMap<String, Integer>>();
public static void main(String[] args) throws IOException {
    BufferedReader read = new BufferedReader(new FileReader(args[0]));
    String temp;
    while ((temp = read.readLine()) != null) {
        if (temp.contains("[")) {
            String[] parts = temp.split("--");
            String[] parts2 = parts[1].split(" \\[");
            Scanner scan;
            scan = new Scanner(parts2[1]).useDelimiter("\\D");
            int o = scan.nextInt();
            map.get(parts[0]).put(parts2[0], o);
        } else {
            map.put(temp, new HashMap<String, Integer>());

        }
    }
    System.out.println("Finished!");
}

}

4

1 回答 1

0

我已经运行了您的代码,下面是到达打印“已完成”的行时的地图:

map = {HashMap@634}  size = 4
 0 = {HashMap$Node@640} "" -> " size = 0"
 1 = {HashMap$Node@641} ""San Antonio"" -> " size = 0"
  key = ""San Antonio""
  value = {HashMap@647}  size = 0
 2 = {HashMap$Node@642} ""San Francisco"" -> " size = 2"
  key = ""San Francisco""
  value = {HashMap@649}  size = 2
   0 = {HashMap$Node@654} "Weed" -> "305"
   1 = {HashMap$Node@655} ""Wisconsin Dells"" -> "2189"
 3 = {HashMap$Node@643} "Washington" -> " size = 1"
  key = "Washington"
  value = {HashMap@651}  size = 1
   0 = {HashMap$Node@662} ""San Jose"" -> "2909"

确切的问题是什么?您是否在地图退出方法之前看到了地图的值?

于 2018-05-01T16:58:28.807 回答