7

I was doing this:

(String[]) myTreeSet.toArray();

but that gives me a ClassCastException at runtime.

The only thing I can think of doing is just making an array first and then iterating through each element in myTreeSet and adding it to the array. It seems like there must be a better way than this. Is there or should I just do this?

Thanks.

Tim
  • 4,295
  • 9
  • 37
  • 49

2 Answers2

21
String[] result = myTreeSet.toArray(new String[myTreeSet.size()]);
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
3

When using toArray() the following happens: a new Object array is being allocated by using new Object[size] and each element from the array will be a reference to one of your strings element. Even if actually points to strings, it's an array with the type Object.

When using toArray(T[] a) the following happens: a new T arrays is being allocated by using

java.lang.reflect.Array
              .newInstance(a.getClass().getComponentType(), size) 

and each from the array will be a reference to one of your strings because a.getClass().getComponentType will return String.class in your case. This time, it's an array with the type String.

Bogdan T.
  • 668
  • 6
  • 13