2

I am working on an assignment and have run into an issue with my code. In the assignment, we are to take in a series of numbers, hash them, then place them into an array where each location is a linked list. I have written the Classes for the linked list (called MyList) and have written the code to place an integer into the array if there is nothing in that arrays position. The issue I am having is that I continue to get "null" for each position in the array when I try to print. Have I made a silly mistake here or is my approach flawed? Thank you.

public class MyHashTab {

public MyHashTab(int initialCapacity, MyList[] anArray) {

}


public static void insert(int searchKey, MyList[] anArray) {

    int hash = searchKey % anArray.length;

    MyList current = new MyList();

    current.iData = searchKey;

    if (anArray[hash] == null) {

        current = anArray[hash];

    }else{

        insertMyList(current, anArray);

    }

}

public static void insertMyList(MyList current, MyList[] anArray) {

    System.out.println("We are here.");
}

public static void printHash(MyList[] anArray) {

    System.out.println("The generated hash table with separate chaining is: ");

    for (int i = 0; i < anArray.length; i++) {

        System.out.println("The items for index[" + i + "]: " + anArray[i]);

    }
}

}

public class MyList {

int iData; // This integer is used as a key value, and as a way to see the actual node instead of it's memory address. 
MyList current;
MyList previous; // This is a pointer to a nodes left child. Pointing seems rude, but they sometimes point to null which, as well know, is less rude. 
MyList next; // This is a pointer to a nodes right child. 

}

1 Answer 1

3

Your insert logic is reversed. Instead of

current = anArray[hash];

it should be

anArray[hash] = current;

I believe you should also be calling insertMyList(current, anArray) regardless of whether the array location was originally null, so the logic should be

if(anArray[hash] == null) {
    anArray[hash] = new MyList();
}
insertMyList(anArray[hash], anArray);
Sign up to request clarification or add additional context in comments.

1 Comment

That did it! Thank you Zim-Zam. I am fairly sure I spend more time on assignment issues than any other error. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.