HashMap containsKey始终为相同的字符串返回false

时间:2018-05-01 15:06:23

标签: java string object hashmap containskey

我正在从一个文件中解析我的城市名称以及以这种格式到其他城市的距离:

"San Antonio" 
"San Francisco" 
Washington 

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

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

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!");
}

}

1 个答案:

答案 0 :(得分: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"

确切的问题是什么?在你离开方法之前,你有没有看到你的地图的价值是什么?