Search code examples
javaserializationcloning

Problem with HashSet Serialization / Cloning


Why is this failing? I am comparing the serialized form of an empty HashSet with the serialized form of its clone created by serialization+deserialization.

import org.apache.commons.lang3.SerializationUtils;
import static org.assertj.core.api.Assertions.assertThat;

...

final HashSet<String> hashSet = new HashSet<>();
assertThat(SerializationUtils.serialize(hashSet))
    .containsExactly(SerializationUtils.serialize(SerializationUtils.clone(hashSet)));

AssertionError will be thrown.

Something must be not correctly serialized/deserialized in a HashSet. Do you have any idea, what exactly? I am Using OpenJDK 8.


Solution

  • It has something with loadingFactor. If the Hashset is instantiated like this, then it works:

    new HashSet(0,0.75f);