使用双数组的地图 get 方法返回 null。

huangapple 未分类评论44阅读模式
英文:

Map with Double Array get method returning null

问题

"Map-Double[]"是创建地图的方式 - 作为哈希地图。
尝试将Double[] [0.0, 0.0]馈送到地图中以获取值,但返回的值为空。

    Scanner input = new Scanner(new File(fileName));
    while (input.hasNextLine()) {
        String[] listed = input.nextLine().split("\\s+");
        Double[] key = new Double[2];
        Double value = 0.0;
        for(int i = 0; i<3; i++) {
            if(i<2) {
                key[i] = Double.parseDouble(listed[i]);
            } else {
                value = Double.parseDouble(listed[i]);
            }
        }

这是代码中的所有重要内容,它只是从文件中读取并将其放入HashMap中。

英文:

"Map-Double[], Double-" is how the map is created - as a hash map.
trying to feed in a Double[] of [0.0, 0.0] into the map to get the value, but the value it returns is null.

    Scanner input = new Scanner(new File(fileName));
    while (input.hasNextLine()) {
        String[] listed = input.nextLine().split(&quot;\\s+&quot;);
        Double[] key = new Double[2];
        Double value = 0.0;
        for(int i = 0; i&lt;3; i++) {
            if(i&lt;2) {
                key[i] = Double.parseDouble(listed[i]);
            } else {
                value = Double.parseDouble(listed[i]);
            }
        }

This is everything important to the code, it just reads from a file and places it inside a HashMap.

答案1

得分: 0

Arrays as Double[] do not have equals/hashcode methods that consider the actual content of the array entries. These methods in an array only match if you use the same instance.

So you can't use an array as a key in a HashMap. Using a List<Double> as a key would work but has other problems. I would recommend a dedicated class with a custom equals()/hashcode() implementation.

Using equals/hashcode with double is also highly problematic.

英文:

Arrays as Double[] don't have a equals/hashcode methods that considers the actual content of the array entries. These methods in array only match if you use the same instance.

So you can't use an array as key in a HashMap, using a List&lt;Double&gt; as key would work but has other problems. I would recomend a dedicated class with a custom equals()/hashcode() implemntation.

Using equls/hashcode with double is also highly problematic.

huangapple
  • 本文由 发表于 2020年4月5日 22:33:52
  • 转载请务必保留本文链接:https://java.coder-hub.com/61044243.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定