Java 将整数集合序列化为字节数组并反序列化回

Java 将整数集合序列化为字节数组并反序列化回,java,arrays,serialization,Java,Arrays,Serialization,我需要对集合进行序列化和反序列化,以便将其存储在需要字节[]的Redis中。我发现一个使用ByteBuffer和IntBuffer进行序列化的代码: byte[] serializeIntegerCollection(Collection<Integer> collection) { ByteBuffer byteBuffer = ByteBuffer.allocate(collection.size() * 4); IntBuffer intBuffer = byt

我需要对
集合
进行序列化和反序列化,以便将其存储在需要
字节[]
的Redis中。我发现一个使用
ByteBuffer
IntBuffer
进行序列化的代码:

byte[] serializeIntegerCollection(Collection<Integer> collection) {
    ByteBuffer byteBuffer = ByteBuffer.allocate(collection.size() * 4);
    IntBuffer intBuffer = byteBuffer.asIntBuffer();
    collection.forEach(intBuffer::put);
    return byteBuffer.array();
}
Collection<Integer> deserializeIntegerCollection(byte[] bytes) {
    ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
    IntBuffer intBuffer = byteBuffer.asIntBuffer();
    return asList(intBuffer.array());
}
byte[]序列化整数集合(集合集合){
ByteBuffer ByteBuffer=ByteBuffer.allocate(collection.size()*4);
IntBuffer IntBuffer=byteBuffer.asIntBuffer();
forEach(intBuffer::put);
返回byteBuffer.array();
}
现在我尝试使用反序列化代码:

byte[] serializeIntegerCollection(Collection<Integer> collection) {
    ByteBuffer byteBuffer = ByteBuffer.allocate(collection.size() * 4);
    IntBuffer intBuffer = byteBuffer.asIntBuffer();
    collection.forEach(intBuffer::put);
    return byteBuffer.array();
}
Collection<Integer> deserializeIntegerCollection(byte[] bytes) {
    ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
    IntBuffer intBuffer = byteBuffer.asIntBuffer();
    return asList(intBuffer.array());
}
集合反序列化IntegerCollection(字节[]字节){
ByteBuffer ByteBuffer=ByteBuffer.wrap(字节);
IntBuffer IntBuffer=byteBuffer.asIntBuffer();
返回asList(intBuffer.array());
}

但是
intBuffer.array()
抛出
UnsupportedOperationException
。它有什么问题以及如何处理该问题?

您可以像序列化一样对其进行序列化。serializeIntegerCollection类必须实现可序列化


您可以像这样反序列化它。反序列化IntegerCollectionClass

ObjectInputStream ois=新的ObjectInputStream(新的ByteArrayInputStream(字节));
@抑制警告(“未选中”)

集合集合=(集合)ois.readObject()

您是否考虑过查阅文档?