Reputation: 11
I'm employing a private lib. One of the objects has a method that delivers either a double or a null.
How could I perform:
if (object.method != null) {
// do some numeric operations with the returned value
}
Additional details:
library = org.apache.commons.collections4.map
class = LRUmap
method = get
My code is:
public class ExampleNode extends GeneralNode {
private LRUMap<Integer, Double> cache;
public ExampleNode() {
this.setCache(new LRUMap<Integer,Double>(100));
}
public void setCache(LRUMap<Integer, Double> lruMap) {
this.cache = lruMap;
}
public double getDatumCacheDebug(int llave){
return this.cache.get((Object)llave,false);
}
}
And then I call:
//outside ExampleNode
if ( actualNode.getDatumCacheDebug(k) != null ) {
Eclipse Neon3 says: "The operator != is undefined for the argument type(s) double,null."
Upvotes: 0
Views: 158
Reputation: 26185
The signature of the library method is:
public V get(Object key,
boolean updateToMRU)
in class LRUMap<K,V>
The returned value is a Double
, and therefore could be null, but it is being unboxed to double
before the null test:
public double getDatumCacheDebug(int llave){
return this.cache.get((Object)llave,false);
}
I suggest changing the signature of this method to return Double
instead of double
, so that the information about whether the result was null is preserved and can be tested. Otherwise, it will throw NullPointerException
if get
returns null.
Upvotes: 0
Reputation: 1321
A working variant of your code will be:
if (object.method != 0) {
// do some numeric operations with the returned value
}
But it is better practice to refactor your method object.method() to return a specific number for your "null cases"- example: a method that is searching for an index in a list - returns the index number if found and -1 if not found or exception is thrown during the search (a null case for the search)
Upvotes: 0
Reputation: 3381
When the method returns a primitive double
(and not the Double
class), it can never be null
. A primitive value will always have a value of its type (i. e. you can't do double d = null;
).
Thus this check would never return true and the compiler does not allow you to do it.
Upvotes: 1