Question

Is it possible to create HashSets with fixed capacities? Specifically one of zero and one of one. I have other HashSets which are convenient and that is the reason I am not using a list or something.

Was it helpful?

Solution

Extend HashSet:

import java.util.HashSet;

public class MyHashSet<Key> extends HashSet<Key> {

    private int limit;

    public MyHashSet(int limit) {
        super();
        this.limit = limit;
    }

    public boolean add(Key key) {
        if (!contains(key) && size() == limit) {
            throw new IndexOutOfBoundsException("Limit exceeded.");
        } else {
            return super.add(key);
        }
    }

    public static void main(String[] args) {
        HashSet<Integer> set = new MyHashSet<Integer>(1);
        set.add(0);
        set.add(1);  // IndexOutOfBoundsException
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top