make IntList serializable

This commit is contained in:
2017-09-28 19:02:43 +02:00
parent 4a762f39b9
commit a178086dfa
2 changed files with 93 additions and 3 deletions

View File

@@ -1,5 +1,10 @@
package org.lucares.collections;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
@@ -413,4 +418,41 @@ public class IntListTest {
return result;
}
@Test
public void testSerialize() throws IOException, ClassNotFoundException {
final IntList emptyList = new IntList(0);
internalSerializeTest(emptyList);
final IntList emptyListWithCapacity = new IntList(10);
internalSerializeTest(emptyListWithCapacity);
final IntList threeElements = new IntList(10000);
threeElements.addAll(1, 2, 3);
internalSerializeTest(threeElements);
final IntList trimmedList = new IntList(10000);
trimmedList.addAll(1, 2, 3);
trimmedList.trim();
internalSerializeTest(trimmedList);
}
private void internalSerializeTest(final IntList list) throws IOException, ClassNotFoundException {
final ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
try (final ObjectOutputStream out = new ObjectOutputStream(byteBuffer)) {
out.writeObject(list);
}
try (ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteBuffer.toByteArray());
ObjectInputStream in = new ObjectInputStream(byteInputStream)) {
final IntList actual = (IntList) in.readObject();
Assert.assertEquals(list, actual);
Assert.assertEquals(
"The capacity of the deserialized list. Should be equal to the number of inserted "
+ "values, because we don't want to serialize the unused part of the array",
list.size(), actual.getCapacity());
}
}
}