ArrayList is replacing item instead of adding it to end

I have a method that finds a node in a linked list with a certain id and adds items to the arraylist of that node.

ArrayList <String> elems;

public Place addElemToLst(String id, String elem) {
        
            // if no nodes create new node
            if (head == null) { 
                Node node = new Node(id);
                node.elems.add(item);
                head = unit;
            } else if (head != null) {
                Node curr = head;
                while (curr.next != null && !curr.next.id.equals(id)) {
                    curr = curr.next;
                }
                // if there is a id match
                if (curr.id.equals(id)) {
                    curr.elems.add(item);
                }
                // add new Node
                else { // the error is in this section
                    Node node = new Node(id);
                    node.elems.add(elem); 
                    curr.next = node;
                    
                }
        
        }

        return this;
    }

The problem is when I call addElemToLst() on an id of lets say “item1” multiple times and keep adding elements to the arraylist, the arraylist will only keep the last item entered into the arraylist. Essential, the arraylist is always a size of 1 because previous entries keep getting replaced. Why is this and what is the error? I have isolated the error to the comment in the code. Thanks

Answer

You are not checking the first element/head for the correct ID

 while (curr.next != null && !curr.next.id.equals(id))

You can try something like this for the second half:

else {
        Node curr = head;
        Node prev = null;
        while(curr != null){                
            if(curr.id == id){
                curr.elems.add(elem);
                return this;
            }
            prev = curr;
            curr = curr.next;
        }
            Node node = new Node(id);
            node.elems.add(elem);
            prev.next = node;

        }
}

Leave a Reply

Your email address will not be published. Required fields are marked *