• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Questions on Collection Interface.

 
Qunfeng Wang
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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

thanks.
 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!

Marco
 
Rob Spoor
Sheriff
Pie
Posts: 20545
56
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic