Given the below example code is there a way to initialise total
such that I do not have to do a null check later when I use it. I am not able to pass the value into the constructor.
public class SampleCode
{
private WeakReference<Float> total;
public SampleCode() {
}
public void setWidget(Float total) {
this.total = new WeakReference<>(total);
}
public float calculatePercentage(Float count) {
if (total == null) {
return -1;
}
if (total.get() == null) {
return -1;
}
return count / total.get();
}
}
I would like to do something like this in the constructor:
this.total = new WeakReference<>(null);
But that doesn't work. Can I initialise a WeakReference in a released state or does that go against the classes purpose?
Thanks
Edit
Thanks for all the feedback.
- The use of float was meant to simplify the question but I can completely understand the confusion. The object actually being held by the weak reference is a view in an Android layout and this class lives outside the activities lifecycle.
- total.get() should be assigned to a local value before it is evaluated
- The statement "This does not work" was in relation to:
total.get() == null
evaluating to false after initialising with this.total = new WeakReference<>(null);
I now understand that statement to be incorrect. This will evaluate to true. However I think it might be better to not initialise it to null and just check the null condition before access.