This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Questions on Collection Interface. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Questions on Collection Interface." Watch "Questions on Collection Interface." New topic

Questions on Collection Interface.

Qunfeng Wang
Ranch Hand

Joined: Jan 28, 2005
Posts: 434

1. What do these optional operations mean?
2. Why do remove(Object)/contains(Object) methods use an Object parameter rather than a generic type?


To be or not to be. It's a question.
Marco Ehrentreich
best scout

Joined: Mar 07, 2007
Posts: 1294

Hi Louis,

not all operations make sense for all implementations of a collection. For example it doesn't make sense to remove something from an unmodifiable collection. So it can simply throw an UnsupportedOperationException instead. Therefore some of the methods are optional.

You can find more information in the API documentation!

Rob Spoor

Joined: Oct 27, 2005
Posts: 20279

As for your second question, this was a deliberate decision by Sun, to break as little code as possible for people migrating.

The thing is, you can try to remove an object of the wrong type. It will just fail. It will still keep the integrity of the Collection intact. Similarly, checking for Object will not cause any problems either. Sure, it will fail every time (return false), but it is still allowed.

That's also why Map.get takes an Object; if it does not match the generic type it will simply not be found and return null.

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Questions on Collection Interface.
jQuery in Action, 3rd edition