Search code examples
javanullhashmapintegertrove4j

TObjectIntMap.get() returns 0 if null Trove


I am using trove library to create hash maps

http://trove.starlight-systems.com/ 

The class I am using is TObjectIntMap in which I had to use the function get. The issue is that get returns 0 if two cases

1- If the value of the specified key is zero

2- If the key does not exist

For example in the following code

TObjectIntMap<String> featuresMap = new TObjectIntHashMap<String>();

        if(String.valueOf(featuresMap.get("B")) == null)
            System.out.println("NULL");
        else 
            System.out.println("NotNull");


        System.out.println(featuresMap.get("B"));

The program will print the following

1- NotNull: because it gets zero. Although the key "B" has not been set

2- Zero: The return of featuresMap.get("B") is zero instead of null.

I have checked their documentation in the link below and it was a mistake that they solved. So get actually return zero instead of null because int cannot be null.

https://bitbucket.org/robeden/trove/issue/43/incorrect-javadoc-for-tobjectintmapget

Now my question is: How to differentiate between a zero and Null in this case. Is their any way around to address this issue.


Solution

  • Try their containsKey method. If the value comes back 0, use that method to check if the map contains the key - if it does, then the key's value really is 0. If it doesn't, then the key is not set.