Search code examples
javasingly-linked-list

Deleting a node in a linked list java


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?


Solution

  • 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.