Hashing Linear Probing

45 Views Asked by At

I want to do linear prob and I want to output the before and after linear probing but then after the linear probing my key is not showing up.

Here's my code:

import java.util.*;

class practice {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        Hashtable<Integer, String> table = new Hashtable<>(10);

        System.out.println("How many students u want to enter: ");
        int numOfSt = sc.nextInt();

        for (int i = 1; i <= numOfSt; i++) {
            System.out.println("ID: ");
            int ID = sc.nextInt();

            System.out.println("Name: ");
            String name = sc.next();

            table.put(ID, name);
        }
        for (Integer key : table.keySet()) {
            System.out.println(key.hashCode() % 10 + "\t\t" + key + "\t\t" + table.get(key));
        }

        Hashtable<Integer, String> LinearProb = new Hashtable<>(10);

        for (Integer key : table.keySet()) {
            int index = key.hashCode() % 10;

            while (LinearProb.containsKey(index)) {
                index = (index + 1) % 10;
            }

            LinearProb.put(index, key + table.get(key));

        }

        for (Integer key : LinearProb.keySet()) {
            System.out.println(key + "\t\t" + key.hashCode() % 10 + "\t\t" + LinearProb.get(key));
        }
    }
}

I tried to fix the output after linear probing

I want to have an output like:

Index ID Number Name
2 212 Ana
:----------------------------:
2 712 Sofia

but then it gave me:

Index ID Number Name
2 2 Ana
:----------------------------:
3 3 Sofia
1

There are 1 best solutions below

0
Dov On

You seem somewhat confused about the purpose of HashMap. They already write linear probing. it's built into the data structure.

If you are being given homework and have to write a hashmap then you have to write your own. Using the built in hashmap will not be acceptable.

If you want to use the library one, why would you want to roll your own linear probing on top of what is already in there, which is vastly superior to what you are writing?

It's not clear what you intend, but when you put two items into a hash map, the second one with the same key replaces the first one. I think that's what you are seeing.