Question

I have a class which extends an Arraylist of generic type:

class ListA extends ArrayList<A>{

}

Now i create an object of ListA and then i want to make it a synchronized list

ListA a = new ListA();
a = (ListA) Collections.synchronizedList(a);

But above code gives typecast exception. The last thing i want to iterate over object a and store list memebers in a different synchronized list.

Any suggestions on how to go about this?

Was it helpful?

Solution

Replace a class inheriting from ArrayList<A> with an interface and a class containing the list:

interface ListA extends List<A> {
    // Put additional methods here
}
class ListAImpl implements ListA {
    private List<A> content;
    public ListAImpl(List<A> content) {
        this.content = content;
    }
    // Use delegation for all methods of the List<A> interface, calling through
    // to the content list.
}

Now the synchronization of your ListA object depends on what you pass to its constructor: pass a "plain" ArrayList<A> to have a non-synchronized ListA, or pass a synchronized one to have a synchronized ListA.

Now your code snippet when you make a synchronized ListA from a non-synchronized one like this:

ListA a = new ListAImpl(new ArrayList<A>());
ListA sync = new ListAImpl(Collections.synchronizedList(a));

OTHER TIPS

Collections.synchronizedList() is declared as follows

public static <T> List<T> synchronizedList(List<T> list) {

In other words, it returns a List. You don't and shouldn't know anything about the implementing class. As such, you cannot expect it to be of type ListA.

Program to interfaces whenever you can.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top