Home > database >  Deleting a node in a linked list storing an object
Deleting a node in a linked list storing an object

Time:05-22

this is the code for the delete method in my linkedList class. This method works perfectly fine when used with integers and strings, but doesn't work when I pass an object as parameters. FYI: In a ListNode, I store its value as an object, i.e, getValue() method returns an object.

    public void delete(Object pObject)
    {
    DSAListNode currentNode=head;

    if(head.equals(pObject))
    {
        removeFirst();
    }
    else if(tail.equals(pObject))
    {
        removeLast();
    }
    else 
    {

     while(currentNode!=null)
    {
        DSAListNode previousNode=currentNode.getPrevious();
        DSAListNode nextNode=currentNode.getNext();

        if(currentNode.getValue().equals(pObject))
        {
              
                previousNode.setNext(nextNode);
                nextNode.setPrevious(previousNode);
        }

        currentNode=nextNode;
    }
    }

This method works well when used with integers and strings, but not with objects, example is given below:

    DSALinkedList list=new DSALinkedList();
    Connection connection1=new Connection("abc", "def", 10, 1, "stairs");
    Connection connection2=new Connection("ghi", "jkl", 10, 1, "stairs");
    Connection connection3=new Connection("mno", "pqr", 10, 2, "construction");

    list.insertLast(connection1);
    list.insertLast(connection2);
    list.insertLast(connection3);
    
    Connection tempConnection=new Connection("ghi", "jkl", 10, 1, "stairs");
    list.delete(tempConnection);

The tempConnection object which is the same as the connection2 object, doesn't get deleted. I think there's a problem in my delete method when checking if 2 objects are equal, is so how can I correct it?

CodePudding user response:

The issue here is that tempConnection is a new object with the same parameters as connection2. In your delete method, you are using the equals to check for equality.

By default, Java will check if they are the same reference. In your case they are not, hence they are not being deleted.

You need to override the equals() method inside your Connection class. Here you will essentially be checking if the parameters are the same, not the references.

Your delete method will then work as expected.

  • Related