Search code examples
javajava-6

Best way to construct a read-only, empty List?


I'm creating an immutable representation of an "event" in my system, and thus for lists of owners passed in the constructor, I'd like to take a read only view of them. Further, if they pass in null for the list, I'd like to make a read-only empty list in that case.

Now, since Collections.unmodifiableList balks at null, I currently have this:

userOwners_ = Collections.unmodifiableList(userOwners != null 
                                           ? userOwners 
                                           : new ArrayList<String>(0));

But that seems a bit ugly and inefficient. Is there a more elegant way to do this in Java?


Solution

  • An equally ugly, but marginally more efficient answer would be

    userOwners_ = userOwners != null ? 
                      Collections.unmodifiableList(userOwners) :
                      Collections.emptyList();
    

    However there are a couple of other things to observe.

    1. It appears that at some point, someone has decided to use null to represent an empty list. That is poor design ... and results in the need for special handling. Better to set it to either a new list, or emptyList() if you know the list is always empty.

    2. If you haven't consciously decided that null is the way to represent an empty list, then that null is "unexpected" and you should juts let it throw an NPE so you can track down and fix the cause. (It could be a variable that you have assumed is initialized elsewhere ... but isn't. That's a bug.)

    3. There is some confusion about whether you want a "read-only" list or an "immutable" list:

      • The unmodifiableList() method gives you a list that you cannot modify; i.e. it is "read only". But the original list can still be modified, and those changes will be visible via the "read only" wrapper.
      • If you want an "immutable" list (i.e. one that cannot be changed at all), you need to clone() the original list, and then wrap the clone using unmodifiableList().
      • Neither of these will make the elements of the list (the "owner" objects) immutable (if they are not already immutable).
    4. The identifier userOwners_ is a code style violation in the most widely accepted / used Java style guide.