Is there a basic Java Set implementation that does

2020-05-31 06:25发布

The API for the Java Set interface states:

For example, some implementations prohibit null elements and some have restrictions on the types of their elements

I am looking for a basic Set implementation that does not require ordering (as ArrayList provides for the List interface) and that does not permit null. TreeSet, HashSet, and LinkedHashSet all allow null elements. Additionally, TreeSet has the requirement that elements implement Comparable.

It seems that no such basic Set exists currently. Does anyone know why? Or if one does exist where I can find it?

[Edit]: I do not want to allow nulls, because later in the code my class will iterate over all elements in the collection and call a specific method. (I'm actually using HashSet<MyRandomObject>). I would rather fail fast than fail later or accidentally incur some bizarre behavior due to a null being in the set.

标签: java api null set
15条回答
forever°为你锁心
2楼-- · 2020-05-31 07:22

Hashtable does not allow null values......

查看更多
【Aperson】
3楼-- · 2020-05-31 07:23

for me, I didn't find one, so I overrode the add function

Collection<String> errors = new HashSet<String>() {
    @Override
    public boolean add(String s) {
        return StringUtil.hasContent(s) && super.add(s);//we don't want add null and we allow HashSet.add(null)
    }
};
查看更多
男人必须洒脱
4楼-- · 2020-05-31 07:25

Yes -- in the docs for com.google.common.collect.ImmutableSet:

A high-performance, immutable Set with reliable, user-specified iteration order. Does not permit null elements.

查看更多
爷、活的狠高调
5楼-- · 2020-05-31 07:25

Why do you not want to allow null?

Do you want to throw an exception if null is added to your set? If so, just do something like this:

private Set<Object> mySet = new HashSet<Object>() {
    @Override
    public boolean add(Object e) {
        if (e == null)
            throw new IllegalArgumentException("null"); // or NPE
        // or, of course, you could just return false
        return super.add(e);
    }
};

HashSet's addAll() calls add() repeatedly, so this is the only method you'd have to override.

查看更多
我想做一个坏孩纸
6楼-- · 2020-05-31 07:26

You may also wish to check out Google Collections. They are more null phobic, I believe.

查看更多
时光不老,我们不散
7楼-- · 2020-05-31 07:26

I am not sure of a type which this is true. But could you not inherit from a collection or HashTable of your choice and override the Add method, throwing an exception if the element is null?

查看更多
登录 后发表回答