In Java library, what is the reason that the Collection
interface doesn't extend Cloneable
and Serializable
interfaces?
Collection
is an interface that specifies a group of objects known as elements. The details of how the group of elements is maintained is left up to the concrete implementations of Collection
. For example, some Collection
implementations like List
allow duplicate elements whereas other implementations like Set
don't. A lot of the Collection
implementations have a public clone
method. However, it does't really make sense to include it in all implementations of Collection
. This is because Collection
is an abstract representation. What matters is the implementation. The semantics and the implications of either cloning or serializing come into play when dealing with the actual implementation; that is, the concrete implementation should decide how it should be cloned or serialized, or even if it can be cloned or serialized. In some cases, depending on what the actual backing-implementation is, cloning and serialization may not make much sense. So mandating cloning and serialization in all implementations is actually less flexible and more restrictive. The specific implementation should make the decision as to whether it can be cloned or serialized.
Here's an explanation from Oracle's documentation:
Many Collection implementations (including all of the ones provided by the JDK) will have a public clone method, but it would be mistake to require it of all Collections. For example, what does it mean to clone a Collection that's backed by a terabyte SQL database? Should the method call cause the company to requisition a new disk farm? Similar arguments hold for serializable.
If the client doesn't know the actual type of a Collection, it's much more flexible and less error prone to have the client decide what type of Collection is desired, create an empty Collection of this type, and use the addAll method to copy the elements of the original collection into the new one.
Because if it did, that would require all Collection
implementations to be Cloneable
and Serializable
, which is more restrictive than needed. Implementations frequently also implement those interfaces, but it's not for the Collection
interface to require it.
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