Search code examples
javaserializationjdk1.7

serialVersionUID without L, xxxxxxxxxxxxxxxxxL vs 1L, positive vs negative


I read What is a serialVersionUID and why should I use it? and static final long serialVersionUID = 1L. From these two SO posts I have a rough idea of what it is. It is an ID for a Serializable class used to check if the sender and receiver are compatible during deserialization. If not a InvalidClassException is thrown.

However I am curious about a few things:

  • serialVersionUID seems to be divided into 2 "type". 19 numbers followed by L xxxxxxxxxxxxxxxxxxxL or 269L or 1L. These numbers don't seem arbitrarily chosen. If we simply need an ID wouldn't any number work? what is the logic behind this design.
  • For the 20 characters long serialVersionUID it can be positive or negative. What is the difference. Again if serialVersionUID is used for the purpose of identifying, why do we need to have a negative number? We have not used up all the positive numbers yet.
  • In MirroredTypedException.java the serialVersionUID is 269 without the L. It is the only serialVersionUID I found without the L. Why is that? What is the meaning of L?

a snapshot (this snapshot doesn't include all of them)

enter image description here


Solution

  • serialVersionUID seems can be divide into 2 "type"

    Not really. They're all just longs.

    For the 20 characters long serialVersionUID it can be positive or negative.

    These are all just randomly chosen. If you randomly choose a number between Long.MIN_VALUE and Long.MAX_VALUE then most of the time it will have 19 digits, and half the time it will be negative.

    Sometimes they might be generated from a hash of something (e.g. sourcecode, an xml definition, etc.). If the hash function is any good, then the distribution of numbers will be the same as if just choosing randomly.

    Why is that? What is the meaning of L?

    L identifies a literal of type long. It's not needed for 269, because it fits in the range of int, and will be automatically upcast to a long.