Darshan Patel
Darshan Patel

Reputation: 3256

Should serialVersionUID be unique for different classes?

class A implements Serializable{
    private static final long serialVersionUID = 5L;
    ...
}

and

class B implements Serializable{
    private static final long serialVersionUID = 6L;
    ...
}

then it is necessary to give unique serialVersionUID to both classes.

So can I assign serialVersionUID = 5L for both classes?

I read following links

Why generate long serialVersionUID instead of a simple 1L?

What is a serialVersionUID and why should I use it?

Upvotes: 28

Views: 14307

Answers (4)

Raman Sahasi
Raman Sahasi

Reputation: 31851

serialVersionUID can be anything.

But the best practice is to start with the lowest number (for example 0L) and update it whenever you make a change in class which affects serialization, for example, adding/updating/removing a field, in which case you should increase the version number from 0L to 1L and so on.

Upvotes: 4

Nitin
Nitin

Reputation: 19

SerialVersionUUID is an identifier used by a compiler to serialize/deserialize an object. This id is a private member to the class.

Creating new uuid for every serializable is good to have control over the serialization/deserialization process but it need NOT be unique among different classes.

Upvotes: 1

Filipp Voronov
Filipp Voronov

Reputation: 4197

Yes, you can. Serial versions of different classes are independent and do not interfere each other.

PS
Eclipse even proposes you to set serialVersionID by default value that is 1L.

Upvotes: 27

Aniket Thakur
Aniket Thakur

Reputation: 68935

serialVersionUID is needed to remember versions of the class. It should be same while serializing and deserializing. It is a good programming practice to provide this value rather than JVM assigning one(generally it is hash). It is not necessary for two classes to have unique values.

Upvotes: 11

Related Questions