Proposal: add unmodifiable() to Collection interface

Gernot Neppert mcnepp02 at googlemail.com
Fri May 25 05:10:00 PDT 2012


Hello,

now that the Collections API is being revised with the help of
'Defender methods', I'd like to suggest adding the following method:

interface Collection<E>
{
...

/**
  Yields an unmodifiable view of this Collection.
  @return an unmodifiable view of this Collection. Can be {@code this}
instance if it is already unmodifiable.
*/
   Collection<E> unmodifiable();
}


For the rationale behind this proposal, consider the following, quite
common example:

public class Company
{
   private final List<Customer> customers;

   public Company(List<Customer> customers) {
       this.customers = new ArrayList<Customer>(customers);
   }

   public Company(List<Customer> customers) {
       this.customers = Collections.emptyList();
   }

   public List<Customer> getCustomers() {
       return Collections.unmodifiableList(customers);
   }
}

As you can see, the method getCustomer() yields an unmodifiable view
of the internal List, gratuitously creating a new instance even for
empty Lists!
The following package-private JDK classes could have overridden
versions of the "unmodifiable" method that simply return "this":

- java.util.Collections.UnmodifiableCollection
- java.util.Collections.EmptySet
- java.util.Collections.EmptyList
- java.util.Collections.SingletonList
- java.util.Collections.SingletonSet


More information about the lambda-dev mailing list