简体   繁体   中英

writeObject and readObject method for a Serializable class which extends ArrayList<E>

I want to extend the ArrayList class to create a collection which doesn't hold duplicate element and use array internally to store. SetUniqueList stores unique element, but I want to add more functionality.

I am stuck in the method writeObject and readObject . This is the implementation in ArrayList :

private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{
    int expectedModCount = modCount;
    s.defaultWriteObject();

    s.writeInt(elementData.length);

    for (int i=0; i<size; i++)
        s.writeObject(elementData[i]);

    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }

}

private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
    s.defaultReadObject();

    int arrayLength = s.readInt();
    Object[] a = elementData = new Object[arrayLength];

    for (int i=0; i<size; i++)
        a[i] = s.readObject();
}

Clearly I cannot access private transient Object[] elementData; . I am puzzled that should I create class like ArrayList , not extending it, or there is any other artcitectural way to do this?

Update

I need to use subList so that changes in the sub list are reflected in this list.

I can think of a couple of ways to implement readObject and writeObject on a subclass of ArrayList :

  • Use reflection to call the private methods in ArrayList (Nasty!! But possibly justifiable.).

  • Use super.iterator() etctera to iterate the elements in your readObject method.


However, I think you would be better off turning your subclass of ArrayList into a wrapper class that delegates operations to a real ArrayList . Just make sure that the wrapper class is Serializable and the private variable containing the reference to the wrapped list is not marked as transient .)

An LinkedHashSet might be another option ... depending on how the collection is used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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