1

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?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Johan Wiström
  • 373
  • 1
  • 5
  • 13
  • 1
    Why cannot you cast it? What's the output when you use `System.out.print(object.getClass().getName())` and `System.out.println(object.getClass().getTypeName())`? You could also use `Class> interfaces = object.getClass().getInterfaces` and get the info of the object at runtime to see what super type you may cast it in order to ease your work. – Luiggi Mendoza Jun 05 '15 at 16:21
  • Are you sure you are casting the object to Set and not some kind of concrete Set? – DJClayworth Jun 05 '15 at 16:58

3 Answers3

2

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.

Lucas Ross
  • 1,049
  • 8
  • 17
0

Set listOfSelectedItems = new HashSet(object)

This is not possible. How about this.

Set<SimpleUserBean> listOfSelectedItems =  new HashSet<SimpleUserBean>();
listOfSelectedItems.addAll((Collection)object);
mehta
  • 735
  • 1
  • 11
  • 26
0

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

Rahul Mane
  • 1,005
  • 18
  • 33
user3785155
  • 69
  • 1
  • 4