Because either (1) UnmodifiableSet implents the Set interface and throws an Invalid operations working at runtime for methods that would modify the set or (2) UnmodifiableSet does not implement the full Set interface, making it possible to catch errors at compile time, but also making it impossible to treat an UnmodifiableSet as a Set. The best solution is to document where you return an UnmodifiableSet versus a regular Set in your Javadocs.
On Mar 23, 2017 08:35, "sebb" <seb...@gmail.com> wrote: > On 23 March 2017 at 15:02, Lukasz Lenart <lukaszlen...@apache.org> wrote: > > 2017-03-23 14:37 GMT+01:00 sebb <seb...@gmail.com>: > >> Not sure I follow. > >> > >> What exactly can the compiler check? > > > > You can declare a variable or a field of type UnmodifiableSet but > > there is no way to create instance of the type UnmodifiableSet - there > > is no such constructor neither factory method :) > > > > You can create an instance: > > UnmodifiableSet<String> us = (UnmodifiableSet<String>) > UnmodifiableSet.unmodifiableSet(new java.util.HashSet<String>()); > us.clear(); // The compiler is happy with this, but it fails at > runtime > > AFAICT the only way the compiler can check is to create a class or > interface that does not have the update methods. > > One could potentially create a ReadOnlySet interface that is > implemented by UnmodifiableSet. > Similarly for the other unmodifiable Collections. > > However would it be worth it? > > > Regards > > -- > > Ćukasz > > + 48 606 323 122 http://www.lenart.org.pl/ > > > > --------------------------------------------------------------------- > > To unsubscribe, e-mail: dev-unsubscr...@commons.apache.org > > For additional commands, e-mail: dev-h...@commons.apache.org > > > > --------------------------------------------------------------------- > To unsubscribe, e-mail: dev-unsubscr...@commons.apache.org > For additional commands, e-mail: dev-h...@commons.apache.org > >