Cast an unmodifiable set

2.8k Views Asked by At

I have a java.lang.Object that I can't cast. When debugging I notice that the Object is an unmodifiable set so I tried to cast it to a set but that didn't work (ClassCastException). Instead I tried

Set<SimpleUserBean> listOfSelectedItems = new HashSet<SimpleUserBean>(object)

But of course that isn't possible either since there is no such constructor for HashSet.

How would I go about solving this?

3

There are 3 best solutions below

0
On

If the Object is a java.util.Collections.UnmodifiableSet or anything else that implements Collection, then you should be able to do new HashSet<>((Collection) object). That makes it clear to the compiler that you're trying to use the HashSet(Collection<? extends E> c) constructor.

0
On

Set listOfSelectedItems = new HashSet(object)

This is not possible. How about this.

Set<SimpleUserBean> listOfSelectedItems =  new HashSet<SimpleUserBean>();
listOfSelectedItems.addAll((Collection)object);
0
On

Convert java.util.Collections.UnmodifiableSet to String arrays.

Use :

object.getValue().toString().replace("[","").replace("]","").split(":")

Assuming object.getValue() will give you java.util.Collections.UnmodifiableSet