Chandra
Chandra

Reputation: 1307

What is difference between Collections.synchronizedCollection and Collections.synchronizedList or Collections.synchronizedSet

We can use the Collections.synchronizedCollection(Collection c) for all objects of type Collection like Set and List right, why we have separate methods like - Collections.synchronizedList or Collections.synchronizedSet.

Upvotes: 0

Views: 834

Answers (3)

Chandra
Chandra

Reputation: 1307

Yes it throws ClassCastException, i looked into the source code of the Collections class, the method Collections.synchronizedCollection(c) returns the wrapper synchronized methods only for Collection type, Where as the Collections.synchronizedList(list) method has the wrapper synchronized methods for all methods of the List, similarly for the Set also.

So have to use the specific synchronized methods in Collections for specific input type.

thanks for help.

Upvotes: 0

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

There are other interfaces that are Collection apart from List and Set e.g. Deque. You could synchronize it using Collections#synchronizedCollection.

Anyway, if you happen to work with synchronized collections, give a look at the classes at java.util.concurrent package. Some of them are CopyOnWriteArrayList (for List) and CopyOnWriteArraySet (for Set).

Upvotes: 1

Louis Wasserman
Louis Wasserman

Reputation: 198033

If you call Collections.synchronizedCollection on a List, then you can't use the List methods on the returned Collection. In the other direction, you can't call Collections.synchronizedList on something that might be an arbitrary Collection, including a Set.

Upvotes: 1

Related Questions