Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typecasting Arraylist

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?

like image 939
Lokesh Avatar asked Aug 01 '26 15:08

Lokesh


1 Answers

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));
like image 152
Sergey Kalinichenko Avatar answered Aug 03 '26 05:08

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!