Doubly linked list removing first element [duplicate] - java

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

Related

Concurrent Exception on Iterator.next() in Java [duplicate]

This question already has answers here:
Why is a ConcurrentModificationException thrown and how to debug it
(8 answers)
Closed 1 year ago.
This is a code snippet to move to next element in the linked list. On debugging, itrPlaylist.next() is triggering a ConcurrentModificationException. I read that the list should not be modified while I am iterating. So, in this case, where did I go wrong? How can it be resolved?
Thanks in Advance.
public boolean nexxt() {
if(this.itrPlaylist.hasNext())
{
if(!bForward)
{
bForward = true;
itrPlaylist.next();
}
System.out.println("Now playing : " + itrPlaylist.next());
return true;
}
else
{
System.out.println("Reached end of " + this.getPlaylistName() + " playlist !");
}
return false;
}
Where is itrPlaylist is defined? Somethng like
itrPlaylist = list.iterator();
Above assignment should have happened after all the inserts have been done to the list. Looks like you have created one instance variable for itrPlaylist. And I think you might be doing
list.add(value);
after itrPlaylist has been initialized.
In that case, code will throw the above mentioned exception. This happens when some other code outside of iterator modifies the list when iterator is already initialized.

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.

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

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

NoSuchElementException error iterator anylogic [duplicate]

This question already has an answer here:
java.util.NoSuchElementException using iterator in java
(1 answer)
Closed 7 years ago.
This is my code:
Iterator<H> iter = ((Main) getOwner()).eH.iterator();
while (iter.hasNext()) {
if (iter.next().z.c > p_l) {
if (r) {
if (iter.next().R) {
if (iter.next().p <= 0.7 * s && iter.next().c_l >= p_l) {
if (s_h == null) {
s_h = iter.next();
} else {
if (iter.next().p <= s_h.price) {
s_h = iter.next();
}
}
}
}
}
}
}
but I am getting this error:
Error during model startup:
java.util.NoSuchElementException
java.util.NoSuchElementException
at java.util.ArrayList$Itr.next(ArrayList.java:839)
at d_w.P.I(P.java:681)
at d_w.P.checkIfI(P.java:649)
at d_w.Main.initModelStructure(Main.java:1072)
at d_w.Main.onStartup(Main.java:2775)
at d_w.Main.start(Main.java:2765)
at com.anylogic.engine.Engine.start(Unknown Source)
at com.anylogic.engine.ExperimentSimulation.r(Unknown Source)
at com.anylogic.engine.ExperimentSimulation.run(Unknown Source)
at d_w.Simulation.executeShapeControlAction(Simulation.java:111)
I really not sure why I am getting this error any suggestion is highly appreciated thanks in advance
Calling .next() will retrieve the next element and advances the iterator. You have multiple .next() calls without checking if there is a next element at all.
If you want to keep using the same element that the .next() initially returned, then, replace the first .next() with H next = iter.next(), then access the next variable.
Every time you call next() you don't get the same element, instead you traverse to the next element of the iterator. You should save this value to a variable and use it.

Categories

Resources