So I have an array full of nodes called "SNodes" (they are a class of my own creation. They are literally just a basic node that holds a single String and a pointer to the next node).
I have a method called insertValue() that takes in the index you want to put a value in and the String you want the SNode to contain. However, if the index passed already contains an SNode in it, I want the new value to become that SNode's "next" node (essentially creating a linked list of nodes in every index space).
private int insertValue(int arrayPos, String element){//Checks for collisions with another SNode, and inserts the SNode into the appropriate spot in the array
SNode targetNode = array[arrayPos];//What I want to be a reference to the node at the desired position in the array
while (targetNode != null){//If an SNode already exists in that position, keeps iterating down until it gets to a non-existant SNode.
targetNode = targetNode.getNext();//getNext is a method in my SNode that just returns a reference to that SNode's "nextNode" variable.
}
targetNode = new SNode(element);
return arrayPos;
}//end insertValue
My problem is that after I run this method, it does not create a new node in the desired array position, even on the first time running when the array spot is null.
If I change the targetNode = new SNode(element); to array[arrayPos] = new SNode(element); it obviously inserts the SNode into the array just fine, so that leads me to believe that what is happening is the new SNode is being created under the variable targetNode, but that targetNode is not linked to the array position after it is instantiated. I assume it is essentially copying the data from the array position on line 2 into the variable, but then becomes its own separate entity.
So how do I have targetNode actually reference and affect the SNode? (That way way when I iterate down through the linked list of nodes in an already-occupied array space, targetNode is pointing to the correct one.)
NOTE: For the sake of simplicity I have left out the lines that use the setNext() method in SNode to link the previous node in the linked list to its next one.