AbstractCollection
implements Collection
. So why is AbstractCollection
there and why do we use Collection
instead of directly using AbstractCollection
?
The AbstractCollection class in Java is a part of the Java Collection Framework and implements the Collection interface. It is used to implement an unmodifiable collection, for which one needs to only extend this AbstractCollection Class and implement only the iterator and the size methods.
Collections are used to store, retrieve, manipulate, and communicate aggregate data.
Java Collection Framework enables the user to perform various data manipulation operations like storing data, searching, sorting, insertion, deletion, and updating of data on the group of elements.
The Collection interface is used to pass around collections of objects where maximum generality is desired. For example, by convention all general-purpose collection implementations have a constructor that takes a Collection argument.
Maybe it is a little late to answer but just in case I want to answer this question.
AbstractCollection
is used since all the child collections share some functionalities in common as Krzysztof said and, since this functionality is common (exactly the same lines of code) we can use inheritance to rehuse that code and make the design cleaner, easier to understand and more maintainable.
We use the interface since an interface defines the "contract" that every class implementing the interface must provide, i.e the methods that the subclasses must have. This question is similar to, why can't we use ArrayList
instead of List, you can do that, but 90% of the times you will be interested on adding/setting, deleting and knowing the size of an ArrayList
and the List
interface assures you that anything that is written after a new somewhere will implement this methods (and others) so you can call them and polymorphism will do the work. Also, using the interface as a reference allows you to change the type of the concrete implementation without changing anything (only the new calls) and also allows you to change the specific type at runtime, using the specific class reference you are constraining yourself to that reference and only that.
Adding to what @Angelixus says in https://stackoverflow.com/a/58513874/139985:
One reason to NOT do this:
AbstractCollection col = (AbstractCollection) someCollection;
is that subtypes of Collection
are NOT guaranteed to extend the AbstractCollection
base class.
It is certainly the case that most (if not all) of the standard collection types do extend this base class. However, this may not apply to all 3rd-party collection classes. If you encounter a collection class that is implemented without extending AbstractCollection
, the above will give either a compilation error or a runtime exception, depending on the declared type of someCollection
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With