繁体   English   中英

Java Map 返回 null 获取方法

[英]Java Map returning null get method


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


所以我有一个 class 读取一个 csv 文件,其中包含 nfl 球员姓名、position、薪水、积分和团队。 DKdata class 读取文件,getPlayers 方法返回 map。 我遇到的问题是,每当我尝试使用 get(key) 时,它只会返回 null。 我在网上阅读了有关等于方法覆盖的内容,但我不确定如何为此实现它。 如果有人可以帮助我或带领我朝着正确的方向前进,我将不胜感激。 下面的代码带有 output。

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;
    }   
}

Output:

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

null

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

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

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

我在网上阅读了一些关于 equals 方法覆盖的内容,但我不确定如何为此实现它。

最简单的选择是让 IDE 为您生成 equals/hashcode。 在 IntelliJ Idea 中,您可以在类中的某个位置点击 Alt+Inster,然后选择equals() and 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()关联的值,因为它的哈希码可能会更改。 当然,您的代码并非如此,因为字符串是不可变的。

如果 ((request.getMobileNo()>0)) {

    savedOtp = otps.get(String.valueOf(request.getMobileNo()));
  }

如何使用null点异常句柄

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM