Why is it that java.util.List
does not implement Serializable
while subclasses like LinkedList
, Arraylist
do? Does not it seem to be against inheritance principles? For example if we want to send a Linkedlist over a network, we have to write:
new ObjectOutputStream(some inputStream).writeObject(some LinkedList);
So far so good, but while reading the object on the other side we have to explicity say LinkedList l = (LinkedList)objectInputStream.readObject();
instead of List l = (List)objectInputStream.readObject();
. If we were ever to change the writing functionality from LinkedList
to say ArrayList
, we will also have to change the reading part. Having List
implement Serializable
would have solved the problem.
util. List itself is not a subtype of java. io. Serializable , it should be safe to cast the list to Serializable , as long as you know it's one of the standard implementations like ArrayList or LinkedList .
List does not implement Serializable because is it not a key requirement for a list. There is no guarantee (or need) that every possible implementation of a List can be serialized. LinkedList and ArrayList choose to do so, but that is specific to their implementation.
Serializing ArrayList: In Java, the ArrayList class implements a Serializable interface by default i.e., ArrayList is by default serialized.
2. The reason the java. lang. Object didnt implement Serializable is because, what if you do NOT want to make certain fields as Serializable and you my mistake missed to add transient to that field, then will be a havoc.
List
does not implement Serializable
because is it not a key requirement for a list. There is no guarantee (or need) that every possible implementation of a List
can be serialized.
LinkedList
and ArrayList
choose to do so, but that is specific to their implementation. Other List
implementations may not be Serializable
.
List is an interface and making it extend Serializable would mean that any implementation of List should be serializable.
The serializable property is not part of the List abstraction and should therefore not be required for an implementation.
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