How to get amount of serialized bytes representing a Java object?

前端 未结 6 562
执笔经年
执笔经年 2021-02-01 20:45

What syntax would I use to get the number of bytes representing a string and compare them to the number of bytes representing an ArrayList holding that string, for

6条回答
  •  旧时难觅i
    2021-02-01 21:19

    You can serialise each object into arrays and compare the length of each array. This is not very accurate, in the general case, but often gives a good approximation.

    Have a look at ObjectOutputStream (which can be used to serialise an object and turn it into Bytes) and ByteArrayOutputStream (which can be used to hold the serialised bytes).

提交回复
热议问题