Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't java.util.List implement Serializable?

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.

like image 635
Swaranga Sarma Avatar asked Feb 07 '11 22:02

Swaranga Sarma


People also ask

Is Java Util list serializable?

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 .

Why list is not serializable?

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.

Is Java Util ArrayList serializable?

Serializing ArrayList: In Java, the ArrayList class implements a Serializable interface by default i.e., ArrayList is by default serialized.

Why is serializable not implemented?

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.


2 Answers

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.

like image 104
Aaron Avatar answered Sep 18 '22 14:09

Aaron


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.

like image 40
Dunaril Avatar answered Sep 20 '22 14:09

Dunaril