This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan 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 Android Security Essentials Live Lessons this week in the Android 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: 430

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: 1280

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: 19655

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.
Similar Threads
Iterator Pattern
Why are Abstract classes with all concrete methods allowed?
I need help with my project! ADT
Collections question