简体   繁体   English

Java:序列化未知的Arraysize

[英]Java: Serializing unknown Arraysize

If I safe an Array and reload it, is there a possibility to get the size if its unknown? 如果我保护阵列并重新加载它,是否有可能获得未知的大小? Thanks 谢谢

What do you mean by "unknown"? “未知”是什么意思? You can get the length of any java array with the length field. 您可以使用length字段获取任何java数组的长度。

int[] myArray = deserializeSomeArray();
int size = myArray.length;

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. 使用ObjectOutputStream存储数组本身。 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? 使用ObjectOutputStream吗?

否,因为数组的长度仅是分配的内存大小除以存储在其中的对象的大小,并且由于没有对象的大小为0,因此您将始终具有适当的长度(可以为0)

如果使用ObjectInputStream.readObject()读取保存的数组,则将使用适当的长度对其进行重构,并且可以使用array.length读取大小。

Attempting to read between the lines... 试图在两行之间阅读...

If you are actually reading array, then (unlike C) all arrays know their length. 如果您实际上正在读取数组,那么(与C不同)所有数组都知道它们的长度。 Java is a safe language, so the length is necessary for bounds checking. Java是一种安全的语言,因此长度是边界检查所必需的。

MyType[] things = (MyType[])in.readObject();
int len = things.length;

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: 在这种情况下,您需要捕获OptionDataException来检测封闭对象的自定义数据的结尾:

private static final MyType[] NOTHING = new MyType[0];

private transient MyType[] things = NOTHING;

private void writeObject(ObjectOutputStream out) throws IOException {
    out.defaultWriteObject(); // Do not forget this call!
    for (MyType thing : things) {
        out.writeObject(thing);
    }
}
private void readObject(
    ObjectInputStream in
) throws IOException, ClassNotFoundException {
    in.defaultReadObject(); // Do not forget this call!
    List<MyType> things = new ArrayList<MyType>();
    try {
        for (;;) {
            things.add((MyType)in.readObject();
        }
    } catch (OptionalDataException exc) {
        // Okay - end of custom data.
    }
    this.things = things.toArray(NOTHING);
}

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. 如果要执行此类操作,最好在实际数据之前将要读取的对象数写为int。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM