There is a function get() that return a value if it is there in ArrayDeque otherwise returns null i.e x can be some value or null. If get() returns x then function B() should perform some computations otherwise should not do anything.
T get()
{
//compute x
return x;
}
void B()
{
int z;
if(y.get()!=null)
{
z=y.get(); // gives null pointer exception
.....
}
}
The problem is that y.get() already returns the value which is not assigned to any variable, thus gives null pointer exception. If i use something like if((z=y.get()) != 0) it gives exception in cases when x is null. How can i achieve this functionality?
I suspect this is an
ArrayDeque<Integer>, right?When you have:
That’s like saying:
Just use:
instead. Then you can test whether
zis null. On the other hand, ify.get()has already returned a non-null value, I’m surprised if it’s then returning anullvalue – you’d expect it to return the same thing twice, right? Are there other threads involved?Additionally, it’s not clear what you mean by this:
I don’t see where the “thus” in here… it’s fine to call a method and not store the return value in a variable. If that’s throwing a
NullPointerException, it would really suggest thatyis null. Of course, all of this would be easier to diagnose if you would post a short but complete program demonstrating the problem.As an aside, it’s not clear why you’re calling
y.get()twice in the first place. I would restructure the code to:Do you really want to call it twice?