• Post Reply Bookmark Topic Watch Topic
  • New Topic

Abstractlist and Collection objects  RSS feed

 
Michael Waserman
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the difference between these two objects in plain English?

Thanks. Michael.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmmm, you always learn from questions. I'd never looked at AbstractList before.

List and Collection are interfaces. If you write a class that implements Collection then you (and others) can use your class any place they would use any other Collection implementation.

When you add "implements Collection" to your class, you promise to implement all the methods defined by Collection. There are quite a few, and that could add up to a lot of typing.

To make things a bit easier Sun provides AbstractCollection. It already implements all the methods required by Collection interface so that they all throw exceptions. The class is abstract so nobody could ever create one, which is a good thing because it wouldn't do anything useful anyhow. If you have existing code that only uses one or two Collection methods and you'd like to make that code use a new class you write, you can extend AbstractCollection and provide the few methods you need. Now your class is very small and clear - it only contains methods you mean to override.

List and AbstractList are the same kind of interface and dummy implementation pair.

There are a couple disadvantages to this trick. 1) You are extending AbstractCollection so you can't extend anything else. 2) If objects of your class fall into the hands of clients who use methods you did not implement they will suddenly start getting unexpected exceptions. If you want to study that idea further, google for "Liskov Substitution Principle"

Did that answer the right question?
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Stan James:
To make things a bit easier Sun provides AbstractCollection. It already implements all the methods required by Collection interface so that they all throw exceptions.


That's not true. Only optional methods (those which are allowed by the specification to do so) throw an UnsupportedOperationException.

The others are either abstract, or are implemented to provide a correct, though possibly not fast, default implementation, making use of the abstract methods.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!