开发者

How to obtain a customized synchronizedList in java?

开发者 https://www.devze.com 2023-03-18 16:22 出处:网络
I have one customized list MyList that extends ArrayList, like this: class MyList extends ArrayList<SomeParticularItem>{

I have one customized list MyList that extends ArrayList, like this:

class MyList extends ArrayList<SomeParticularItem>{
   [some methods...]
}

Since I have concurrent reads and writes to the list, I want to synchronize it:

MyList mylist = (MyList) Collections.synchronizedList(new MyList());

This seems to be fine, the .jar is build. Then, at runtime, I get:

java.util.Co开发者_开发百科llections$SynchronizedRandomAccessList cannot be cast to MyList

Is there a better way (is there any way at all) to obtain a synchronized list of a list that inherits from some java.util.List?


Well why not make MyList synchronized, alternativly simply use the List interface List mylist = Collections.synchronizedList(new MyList());

Edit: You could of course let MyList extend Vector, since all of the Vectors methods are already synchronized you save some work.


The easiest way to do it would be to extend Vector instead of ArrayList. You could also synchronize the methods of MyList yourself if you wanted to keep it as an ArrayList.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号