Tell me more ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Possible Duplicate:
Why were Java collections implemented with “optional methods” in the interface?

I was looking at the javadoc for Collections and I noticed the unmodifiableCollection/unmodifiableList/etc. methods and I thought to myself, could this API be better?

Here's one of the API signatures:

public static <T> List<T> unmodifiableList(List<? extends T> list)

If you're not too familiar with Java Generics, you can think of it this way:

public static List unmodifiableList(List list)

And the Javadoc says

Returns an unmodifiable view of the specified list. This method allows modules to provide users with "read-only" access to internal lists. Query operations on the returned list "read through" to the specified list, and attempts to modify the returned list, whether direct or via its iterator, result in an UnsupportedOperationException.


Specifically I'm questioning the decision to return a List interface. Why not return a new interface named UnmodifiableList? The upside is you could make your APIs self documenting. The way it is now, a programmer will have to wait until runtime or read documentation to realize he's using the list wrong. He could have written a lot of code by then.

share|improve this question
So it is :) How do I close this? Should I just vote to close my own issue? – tieTYT Jan 10 at 19:42
if you vote to close yourself it should close immediately (I think) – ratchet freak Jan 10 at 19:43
Apparently not :T Either way, thanks for finding that. – tieTYT Jan 10 at 19:45
heh it was my first here of course I'd remember that – ratchet freak Jan 10 at 19:46

marked as duplicate by ratchet freak, gnat, tieTYT, Walter, GlenH7 Jan 10 at 20:15

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer

Because reading documentation is expected. It's documentation.

share|improve this answer
5  
This isn't a good justification - the immutability of the list could be 'documented' by the type system. Some other function taking the list as a parameter will not necessarily know that it cannot be modified, or where it was initially constructed. – Lee Jan 10 at 19:19
@Lee that is a different question (prolly like "why isn't Java as strongly typed as, say, Haskell?") – sparkleshy Jan 12 at 16:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.