Java Map get 方法返回 null

标签 java dictionary null

<小时/>

我的愚蠢错误。我传入的字符串键有括号,但我没有意识到这一点。我在 key 中添加了 .replace() ,现在一切都很好。感谢您的回复。

<小时/>

所以我有一个类读取 csv 文件,其中包含 nfl 球员姓名、位置、薪水、积分和球队。 DKdata类读取文件,getPlayers方法返回 map 。我遇到的问题是,每当我尝试使用 get(key) 时,它只返回 null。我在网上阅读了有关 equals 方法重写的内容,但我不确定如何实现它。如果有人可以帮助我或引导我走向正确的方向,我将不胜感激。下面的代码带有输出。

import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

public class Test {

    public static void main(String[]args) throws FileNotFoundException {
        Map<String, Player> players = new HashMap<String, Player>();
        DKdata d = new DKdata();
        //players.putAll(d.getPlayers());
        
        Player p = new Player("WR","Kev", 1000, 99, "Pit");
        String name = p.name;
        players.put(p.name, p);
        System.out.println(players.get(name).salary);
        
        players.putAll(d.getPlayers());
        System.out.println(players.get("Zach Ertz").salary);
    }
}

public class DKdata {
    private Map<String, Player> players;
    private Scanner scanner = new Scanner(new File("/Users/kevinrhea/Documents/DraftKing/DKsalaries.csv"));
    
    public DKdata() throws FileNotFoundException {
        try {   
            players = new HashMap<String, Player>();
            scanner.useDelimiter(",");
            scanner.nextLine();
            while(scanner.hasNext()){
                String[] data = scanner.nextLine().split(",");
                Player player = new Player(data[0], data[1], Integer.parseInt(data[2]), Double.parseDouble(data[4]), data[5]);
                players.put(data[1], player);
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public Map<String, Player> getPlayers(){
        return players;
    }   
}

输出:

{"Zach Ertz"=Player@2503dbd3, "Jacoby Brissett"=Player@4b67cf4d, "Brandon Bolden"=Player@7ea987ac, ...

null

最佳答案

Map.get() 在两种情况下返回 null:

  1. map 不包含与提供的键关联的值
  2. 与该键关联的值为 null

如果您想区分这两种状态,可以使用 map.contains() 方法,该方法根据键是否存在于 map 中返回 true/false。

I read online something about equals method overriding but I am not sure how to implement it for this.

最简单的选择是让 IDE 为您生成 equals/hashcode。在 IntelliJ Idea 中,您只需在类中的某个位置按 Alt+Inster,然后选择 equals() 和 hashcode()。如果您想自己编写它,那么您必须遵循这些方法的约定:

等于(来自 javadoc):

It is reflexive: for any non-null reference value x, x.equals(x) should return true.
It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
For any non-null reference value x, x.equals(null) should return false. 

哈希码(来自 javadoc):

Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables. 

需要注意的是,映射中的键必须是有效不可变的。这意味着一旦您将给定的键放入映射中,您就不能修改它,否则您将无法 get() 关联的值,因为它的哈希码可能会更改。当然,您的代码并非如此,因为字符串是不可变的。

关于Java Map get 方法返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39565984/

相关文章:

python - 遍历除 x item items 之外的 dict

class - Groovy: map 文字上的 getClass 方法返回 null

f# - 选项类型和可为空类型之间有什么区别?

javascript - 为什么在 JavaScript 中有一个 `null` 值?

java - 如何正确关闭java-ee websocket连接

Java 无法替换后跟的字符串\n

python - Python 字典中的平均值

java - 我正在尝试插入数据库。n 出现错误 "java.lang.IllegalArgumentException: attempt to create saveOrUpdate event with null entity"

java - 在列表中加载静态图像会减慢滚动速度

Python - 列表 : How To Remove Empty Attributes From a List of Dictionaries With Nested Properties?