创建一个空的HashSet

时间:2014-02-10 10:21:38

标签: java hashset

是否可以创建具有固定容量的HashSet?特别是零和一个之一。我有其他方便的HashSets,这就是我没有使用列表或其他东西的原因。

1 个答案:

答案 0 :(得分:0)

扩展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
    }
}
相关问题