ArrayList does not satisfy generic serializable list type

246 Views Asked by At

Given the following java code:

public static <I extends Serializable, L extends List<I> & Serializable> L getList() {
    return new ArrayList<I>(); // <-- Compile error
}

Given that ArrayList do extend both Serializable and List, why does it produce a compile error?

Incompatible types. Found: 'java.util.ArrayList<I>', required: 'L'

1

There are 1 best solutions below

0
Gábor Lipták On BEST ANSWER

I came up with this solution:

public interface SerializableList<T> extends List<T>, Serializable {
}

public class SerializableArrayList<T> extends ArrayList<T> implements SerializableList<T> {
    public SerializableArrayList(int initialCapacity) {
        super(initialCapacity);
    }

    public SerializableArrayList() {
    }

    public SerializableArrayList(Collection<? extends T> c) {
        super(c);
    }
}

Then whenever I need a Serializable List type, I can use the SerializableList interface and its implementation SerializableArrayList