简体   繁体   中英

Java Map returning null get method


Stupid error by me. The string key I was passing in had parenthesis and I didn't realize that. I added a.replace() to the key and everything is good now. Thanks for the responses.


So I have a class that reads a csv file that contains nfl players name, position, salary, points, and team. The DKdata class reads the file, getPlayers method returns the map. My problem I am having is that whenever I try to use get(key) it only returns null. I read online something about equals method overriding but I am not sure how to implement it for this. If anyone can help me out or lead me in the right direction that will be greatly appreciated. Code below with 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() returns null in two cases:

  1. The map does not contain a value associated with the provided key
  2. The value associated with the key is null

If you want to differentiate between those two states you can use the map.contains() method which returns true/false depending on whether the key is present in the map.

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

The easiest option is to let the IDE generate the equals/hashcode for you. In IntelliJ Idea you can just hit Alt+Inster somewhere inside the class and then select equals() and hashcode() . If you want to write it on your own then you have to follow the contract of those methods:

Equals (from the 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. 

Hashcode (from the 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. 

It's important to note that the keys in a map must be effectively immutable. This means that once you put a given key in a map you must not modify it otherwise you'll not be able to get() the associated value, because it's hashcode may change. Of course that' snot the case with your code because strings are immutable.

if ((request.getMobileNo()>0)) {

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

how to use null point exception handle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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