This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
this method is giving me a null pointer exception and I don't know why that is. Is there something wrong with the recursion code?
public void clearAllSelections(){
//Recursively clear all the selections in the sub-tree of this node
//basis:
isSelected = false;
if(isLeaf()) return;
//recursion:
childrenRight.clearAllSelections();
childrenLeft.clearAllSelections();
}
Your isLeaf() check is not sufficient, since a node in a binary tree may have a single child, so you must add null checks :
public void clearAllSelections(){
//Recursively clear all the selections in the sub-tree of this node
//basis:
isSelected = false;
if(isLeaf()) return;
//recursion:
if (childrenRight != null)
childrenRight.clearAllSelections();
if (childrenLeft != null)
childrenLeft.clearAllSelections();
}
do a null check on childrenRight and childrenLeft before making the function call
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 months ago.
I am trying to write a program that deletes a student from a singly linked list.
for (SNode ptr = studentsInLine; ptr.getNext() != null; ptr = ptr.getNext()){
for (SNode target = studentsInLine.getNext(); target.getNext() != null; target = target.getNext()){
if (target.getStudent().getFirstName() == firstName && target.getStudent().getLastName() == lastName){
ptr.setNext(target.getNext());;
}
}
}
I am trying to iterate through my linked list with ptr and target and if target ever equals first and last name then set the ptr.next to target.next. However when I run it there are no updates made to my linked list, and it remains the same as before after I run this code. What am I missing?
You should not use == (equality operator) to compare strings because they compare the reference of the string, instead try to use target.getStudent().getFirstName().equals(firstName) this should compare the strings value for equality.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
The problem arises in the merge function at 'while(m.next!=null)'. It throws a "NullPointerException".
public class Linked {
node ptr1;
node ptr2;
void merge()
{
node m=ptr1;
while(m.next!=null)
m=m.next;
m.next=ptr2;
}
void printmerged()
{
node m=ptr1;
while(m.next!=null)
System.out.print(m.data+", ");
System.out.println(m);
}
}
I added comments to your code to explain to you what's going on.
node ptr1; //ptr1 is null here
node ptr2;
void merge()
{
node m=ptr1; //you are assigning null to m
while(m.next!=null) //you are accessing the "next" property of a null object
m=m.next;
m.next=ptr2;
}
You have to instantiate your objects otherwise they are going to be null.
This question already has answers here:
Null check chain vs catching NullPointerException
(19 answers)
Check if last getter in method chain is not null
(3 answers)
Closed 5 years ago.
I have an object and i want to check if this object or nested fields are null. I want to print this neted field, but i should check if there is null in some level, otherwise i will get null pointer exception .
I know i can do this:
if( object != null && object.A != null && object.A.B != null && object.A.B.C != null && object.A.B.C.D != null) { doSomething( object.A.B.C.D);}
but its so long. Do you know better way to check it ?
Optional is a good way in Java 8.
String value = foo.getBar().getBaz().toString();
With optional it will be:
String value = Optional.ofNullable(foo)
.map(Foo::getBar)
.map(Bar::getBaz)
.map(Baz::toString)
.orElse("EmptyString");
You could implement an interface on all objects with method that returns all child objects and create a method that calls itself recursively to verify that all objects are set.
Let assume that this is a check to prevent misuse of a method, so this should not occurs too many time.
Simply catch this exception, this will invalidate the value.
private boolean isValid(YourObject object){
try{
return object.A.B.C.D != null;
} catch (NullPointerException npe){
return false;
}
}
Of course, don't use this solution if you are doing a lot of validation and those return false to often, exception are an heavy process.
EDIT :
As Fildor point it out, there is a cost to use a try-catch even without exception. But using this answer I can assume this will be limited and there is not much optimization to do on this unique line.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm pretty new to java, and my doubly linked list addFront method and addRear method works fine, but only dequeue method doesn't works. In the main method, I making a test to remove front element using dequeueFront ()method, when I remove front element it works, but If I continued removing front element,
Exception in thread "main" java.lang.NullPointerException
at DoublyLinkedDeque.dequeueFront(DoublyLinkedDeque.java:97)
comes out,
Line97 is the frontNode.previous=null
I just wondering how to remove front element form the double linked list properly.
public E dequeueFront() throws NoSuchElementException
{
if(frontNode!=null)
{
E frontElement=frontNode.element;
frontNode=frontNode.next;
frontNode.previous=null;
frontNode.next=null;
numElement--;
if(numElement==0)
rearNode=null;
return frontElement;
}
else
throw new NoSuchElementException();
}
frontNode=frontNode.next;
If there is no next after frontNode, then frontNode.next returns null.
If frontNode is null then trying to do:
frontNode.previous=null;
Will throw a null pointer exception because how can you access the previous node from a node that doesn't exist? Without thinking about how to make it work with your implementation, just doing a null check will stop this from happening.
if(frontNode != null){
frontNode.previous = null;
}
You will have to do this check with the ".next" also
Or, maybe you can check if numElements = 1. I'll let you think of how to solve that problem.
It should look more like
public E dequeueFront() throws NoSuchElementException {
if(frontNode!=null)
{
E frontElement=frontNode.element;
N oldFront = frontNode ;
frontNode=oldFront.next; // frontNode may now be null
if( frontNode != null ) frontNode.prev=null; // remove link to oldFront
oldFront.previous=null; // should be unessary
oldFront.next = null ;
numElement--;
if(numElement==0)
rearNode=null;
return frontElement;
}
else
throw new NoSuchElementException();
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I just want to know why the compiler allow to continue the program normally in the first condition:
public void ButtonOnClickDirectoryList(View v){
try {
if (!spnOptionSelectedDepartment.equals(null) && !spnOptionSelectedCities.equals(null)) {
if (!spnOptionSelectedTypes.equals(null)) { //code....}
the spnOptionSelectedDepartment and spnOptionSelectedTypes are Strings and are defined at the begining of the class like this:
private String spnOptionSelectedDepartment = null;
private String spnOptionSelectedCities = null;
private String spnOptionSelectedTypes = null;
so when I press the button, it call this method and this are the values that I have in the moment:
spnOptionSelectedDepartment = "9999"
spnOptionSelectedCities = null
spnOptionSelectedTypes = null
so when I put a break point on this condition it just continue validating the rest of the code inside that if...
Could anybody explain me why this behavior?
Let me edit the question, Yes it throws nullpointer exception on the second if...
if (!spnOptionSelectedTypes.equals(null)) {
but why it allows the first IF when spnOptionSelectedCities = null...?
It shouldn't continue, it should throw a NullPointerException that you may intercept in the catch block.
When you try
if (!spnOptionSelectedTypes.equals(null))
it should throw this exception because spnOptionSelectedTypes is null so it is not a String and does not have any equals() method.
Edit:
It allows the first if to pass because it has 2 tests
if (A OR B) {
If A is true, the B condition is not tested because only one is required to continue, because of the OR operator.
Edit 2:
With:
if (A AND B) {
If A is true, B will also be tested and throw a NullPointerException if spnOptionSelectedCities is null.
Definitive answer:
Null tests in Java
if (x != null && y != null) {
x.doSomething();
y.doSomethingElse();
}