How to add an element to a null Set<class>?

I've got a set of elements of a custom class User. Now I simply cannot figure out, how this class could be instantiated. I even tried it by creating another object and pulling the EMPTY set from there like this:

Site mySite = new Site(/*some params here*/);
User newUser = new User(/*some other params here*/);
Set<User> users = mySite.getUsers();
users.add(newUser);
mySite.setUsers(users);

But since mySite.users is null (not empty), I of course get a NullPointerException.

So, what is the right way? I'd be very grateful and hope this is not to vague!

Cheers, Stacky

Jon Skeet
people
quotationmark

There's a huge difference between a reference to an empty set, and a null reference. (Just like there's a huge different between a reference to the empty string, and a null reference.)

It sounds like you should probably change your Site class (or whatever the type of mySite is) so that getUsers() returns an empty set instead of a null reference when there are no users. In general, empty collections are easier to work with than null references - it saves constantly having to perform nullity checks.

people

See more on this question at Stackoverflow