Set

Hash set offers a data structure that offers complexity of O(1) to insert and obtain element from it. We need to be able to calculate hash or position of element based on its value.

If you are interesting in sets, have a look at this chapter in Java Handbook.

Here is a naive implementation of hash set.

class MyHashSet {

    private Integer[] values = new Integer[1000000];

    public void add(int key) {
        values[hash(key)] = key;
    }

    public void remove(int key) {
        values[hash(key)] = null;
    }

    /** Returns true if this set did not already contain the specified element */
    public boolean contains(int key) {
        return values[hash(key)] != null;
    }

    public int hash(int value) {
        return values.length % value;
    }
}

We can perform the following with the hash set we have created.

Advanced hashing and re-sizing hash set.

Lets create simple hash set to demonstrate how they are implemented. We can put couple of items into this hash set. If we would like to expand values array when more elements come, we would have to add more check and resizing. But this is omitted from this implementation for easier understanding.

Now we can try to put and remove some elements.

Observe how are the values placed in the array.

Linked List to handle equals values but the same positions

Here is the output.

Last updated

Was this helpful?