Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to do Collections.EMPTY_SET in Generics?

843793Oct 24 2002 — edited Nov 1 2002
In non-Generic code, I sometimes use Collections.EMPTY_SET:
public class Test
{
    private Set setWhichCanBeNull;

    public Test( Set setWhichCanBeNull )
    {
        this.setWhichCanBeNull = setWhichCanBeNull;
    }

    public Set getSet()
    {
        return ( setWhichCanBeNull == null )
            ? Collections.EMPTY_SET
            : setWhichCanBeNull;
    }
}
If I write this using Generics, Collections.EMPTY_SET does not work, since it does not know what type I am interested in:
public class Test<E>
{
    private Set<E> setWhichCanBeNull;

    public Test( Set<E> setWhichCanBeNull )
    {
        this.setWhichCanBeNull = setWhichCanBeNull;
    }

    public Set<E> getSet()
    {
        return ( setWhichCanBeNull == null )
            ? Collections.EMPTY_SET
            : setWhichCanBeNull;
    }
}
Is there any way to specify something like this:
Collections<E>.EMPTY_SET
or am I stuck with having to write:
    public Set<E> getSet()
    {
        return ( setWhichCanBeNull == null )
            ? new HashSet<E>()
            : setWhichCanBeNull;
    }
Thanks.

Geoff

Comments

Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on Nov 29 2002
Added on Oct 24 2002
5 comments
163 views