Java:序列化未知的Arraysize
如果我保护一个数组并重新加载它,如果它的大小未知,是否有可能获得它的大小? 谢谢
If I safe an Array and reload it, is there a possibility to get the size if its unknown?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
你所说的“未知”是什么意思? 您可以使用长度字段获取任何 java 数组的长度。
What do you mean by "unknown"? You can get the length of any java array with the length field.
听起来您正在序列化并将各个对象存储在数组中(在行与行之间进行了大量阅读之后)。 使用 ObjectOutputStream 来存储数组本身。 如果存储在数组中的对象是可序列化的,它们也会被存储。 当您反序列化时,您将完整地恢复整个数组。
It sounds like you're serializing and storing the individual objects in the array (after much reading between the lines). Use the ObjectOutputStream to store the array itself. If the objects stored in the array are serializable, they'll be stored too. When you deserialize you'll get the entire array back intact.
我认为你需要提供更多信息。 你如何保存数组? 使用对象输出流?
I think you need to supply some more information. How are you saving the array? Using an ObjectOutputStream?
否,因为数组的长度只是分配的内存大小除以存储在其中的对象的大小,并且由于没有对象的大小为 0,因此您将始终拥有正确的长度(可能为 0)
No because the length of the array is just the size of memory allocated divided by the size of the object stored in it, and since no objects have a size of 0 you will always have a proper length, (which could be 0)
如果您使用 ObjectInputStream.readObject() 读取保存的数组,它将被重新构造为适当的长度,您只需使用 array.length 读取大小即可。
If you use ObjectInputStream.readObject() to read the saved array, it will be reconstituted with the proper length and you can just read the size with array.length.
尝试读取字里行间...
如果您实际上正在读取数组,那么(与 C 不同)所有数组都知道它们的长度。 Java是一种安全语言,因此长度对于边界检查是必要的。
也许您的困难在于您正在进行自定义(反)序列化并写出数组的各个元素(提示:不要 - 使用数组)。 在这种情况下,您需要捕获 OptionDataException 来检测封闭对象的自定义数据的结尾:
如果您打算执行此类操作,最好在实际数据。
Attempting to read between the lines...
If you are actually reading array, then (unlike C) all arrays know their length. Java is a safe language, so the length is necessary for bounds checking.
Perhaps your difficulty is that you are doing custom (de)serialisation and are writing out individual elements of the array (hint: don't - use an array). In the case you need to catch OptionDataException to detect the end of the enclosing object's custom data:
If you are going to do that sort of thing, it's much better to write out the number of objects you are going to read as an int before the actual data.