Pregunta

I am creating a chained hash table that uses my own LinkedListclass to handle collisons. Here is where my issue is occuring: I start with an array of LinkedLists, my "hash table", intially set to null. When i wish to add a word, if the desired location is null, I create a new LinkedList, place it in that array index. I then create a new LinkedListNode and set the head of the new LinkedList to the new node.

My issue is occuring here: Whenever I set the head of my new LinkedList to my new LinkedListNode all of my previously created linkedlists also have their head changed to the new node.

My debugger shows that I am truly creating new linkedlists every time. I was afraid each array index was just pointing to a single array, but that is evidently not the issue. Below is all the relevant code

public class SetOfStrings {

private int arraySize;
private LinkedList[] mainArray;
private int totalCount;

//other methods here

public boolean add(String toAdd)
{
    int hashToAdd = hash(toAdd);
    int wasFound = contains(toAdd);
    if(wasFound> 0)
    {
        return false; // means its already in the table
    }
    if(mainArray[hashToAdd]== null)
    {
        mainArray[hashToAdd] = new LinkedList();
        ListNode newHead = new ListNode(toAdd);
        mainArray[hashToAdd].setHead(newHead);
        totalCount++;
        return true;
    }
    ListNode currentHead = mainArray[hashToAdd].getHead();
    ListNode newNode = new ListNode(toAdd);
    newNode.setNext(currentHead);
    mainArray[hashToAdd].setHead(newNode);
    totalCount++;
    return true;

}

public class ListNode {

private String thisString;
private ListNode next;

public ListNode(String setString)
{
    thisString = setString;
    next = null;
}

public class LinkedList {

private static ListNode head;
private static  int count;
private static  ListNode currentPosition;

// other methods here

public  void setHead(ListNode newNode)
{ head = newNode;}

SUMMARY: Whenever I set the head of a Linked List to a new node, it changes the head of all my linked lists to point to the same new node

¿Fue útil?

Solución

You are declaring your head as static. This means that it is shared between all instances of the LinkedList class. Removing the static keyword should fix the issue you described.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top