简体   繁体   中英

Search function in HashTable

public class HashTable {


    /* Class containing next node and key and name value*/
    class Node { 
        private long key;

        public long getKey() {
            return key;
        }

        public void setKey(long key) {
            this.key = key;
        }

        private String value;

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

        Node next; 

        public Node getNext() {
            return next;
        }

        public void setNext(Node next) {
            this.next = next;
        }

        Node(long key, String value) {
            this.key = key;
            this.value = value;
            next = null;
        }
    } 

I'm not sure if I should be creating Node[] size like this.

Node[] size;

    //The hash table array
    Node[] array = null;
    //hash table size. We typically choose m to be a power of 2
    int m = 0;

    // Constructor 
    HashTable(int size) {  
        m = size;
        array = new Node[size];  
    }

    HashTable() {  
        this(100);
    } 

    // Search for a given key in the hashtable
    // Note: you need to use hashFunction(long key) to determine the slot (array index) you will search in
    public Node search(long key) 
    { 
        Node node = null;
        /**
         * TODO
         */
        int hash = hashFunction(key);
        Node list = size[hash];
        while(list!=null) {
            if(list.getKey() == key) {
                return list;
            }
            else {
                list = list.getNext();
            }
        }
        return node;
    }

My hashFunction(long key) works, but I'm having trouble implementing the logic for the search function. I'm not sure what I'm doing wrong. Can someone please help. My implementation for Search starts from public Node search(long key) .

You are using Node list = size[hash] ; in the search but As I can see in the parameter constructor you are using array = new Node[size]; to initialize it.

So, Try to replace size[hash] with array[hash] .

In your pasted code I haven't seen any use of Node []size declaration. You can remove the size array variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM