Long Primitive Nan Value Wanted
Scenario: 1) I Have a Long State Variable That Can Either Be Set or Not Set. 2) This Long Variable Has Valid Values from Long. Min_Value to Long. Max_Value...
Scenario:
1) I have a long state variable that can either be set or not set.
2) This long variable has valid values from Long.MIN_VALUE to Long.MAX_VALUE including zero
3) This is performance sensitive code so I don't want to use a Long wrapper type
How do I write an 'is set' kind of check for this long? Do I really have to add a second boolean value to test whether the long is valid or not? This seems sloppy. I know I could use a Long wrapper here but this seems like a performance waste to be creating so many objects and checking for null.
Pseudo Code (this is sort of what I want):
class foo {
long someLong = NaN; //NaN = hypothetical not a number like Double
public reset() {
someLong = NaN;
}
public doSomethingElse() {
if(someLong !=NaN) {
//report
reset();
}
}
public doSomeStuff() {
if(someLong == NaN) {
someLong = //something
}
}
}
}
4 Answers
You'd have to set aside a special value for NaN. If you really use all possible values, there is none.
Are you sure Long objects are that much of a performance problem?
If so, maybe have an extra boolean to denote if the value is set or not?
Use a Long instead of a long, and use null as the NaN value.
There is no NaN for a long. If you're sure that performance is critical (I'd test the speed penalty of using a Long), then you'll want to use another flag value.
I have used Long.MIN_VALUE as its has odd properties like
Long.MIN_VALUE == -Long.MIN_VALUE
Its also less likely to occur naturally.
The problem with using it is, it can make the code more complex. For this reason I have use double instead integer values less than +/- 2^53 can be represented without error.