Deleting a node in a linked list java [duplicate] - java

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.

Related

Why is the link list merge function not working in Java? [duplicate]

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.

Using orElse() to return a default value [duplicate]

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.

ConcurrentModificationException -> How can I change my code to stop it from throwing this error? [duplicate]

This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
(31 answers)
Closed 5 years ago.
for (FPlayer p : fPlayer.getFaction().getOnline()) {
p.setFaction(null);
}
Basically, the getOnline method returns an array list of the current FPlayers that are online. When the FPlayer is removed from their faction, the faction is set to null (p.setFaction(null)).
I cannot think about how to change my code to stop it from throwing the ConcurrentModificationException. I have used an iterator but still, it.next().setFaction(null) still throws the same exception.
EDIT:
USING A LIST ITERATOR:
ListIterator<FPlayer> it = fPlayer.getFaction().getOnline().listIterator();
while (it.hasNext()) {
it.next().setFaction(null);
}
Caused by: java.util.ConcurrentModificationException
At the line
it.next().setFaction(null)
EDIT #2:
Set faction method:
public void setFaction(Faction faction) {
if (hasFaction()) {
this.faction.getOnline().remove(this);
}
this.faction = faction;
if (faction != null) {
this.faction.getOnline().add(this);
}
}
This is happening because while iterating you are removing the data from the list .
Couple of solutions .
If the list size is small convert it to array and then loop over
Use for loop for iteration .
for(int i=0;i<fPlayer.getFaction().getOnline().size();i++)
{
// Condition to check if true
if(true)
{
fPlayer.getFaction().getOnline().remove(i);
i--;
}
}
Yes, change your code so it doesn't change the collection inside the loop you are running. For example, create a copy of the collection before iterating.
for (Foo foo : new ArrayList(myFoos)) {
if (foo.isBar()) {
myFoos.remove(foo);
}
}
Iterating and changing the list without the new ArrayList() would have caused a ConcurrentModificationException

Doubly linked list removing first element [duplicate]

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();
}

Java null pointer exception on recursive binary tree method [duplicate]

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

Categories

Resources