Just for the pleasure of learning, I don´t need an alternative solution (I know JList is generic in Java7), thanks!
What I am looking would be something like this…
private <U,T> U<T> jListSelected2Coll(JList list, Class<U extends Collection<T>> type{
Collection<T> coll = XX;//Getting an instance of type
Object[] array = list.getSelectedValues();
Collections.addAll(coll, Arrays.copyOf(array, array.length, type.subtype_inside_the_T.class));
return coll;
}
This would be called something like
TreeSet<String> selectedItems = jListSelected2Coll(list,TreeSet<String>.class)
I know its complex and particular, but I don´t know what strategy to follow, maybe some black swan action 🙂
Is there any way to acomplish that? Thanks!
Because of Java type erasure, what you are trying to achieve cannot be done directly in Java. However, there are some tricks to pretty much get what you would expect.
Here are two solutions (more or less acceptable):
The second alternative also “works” but is not as safe as the first one (because you cannot express
Class<U extends Collection<T>>in Java):In both cases, if the selected values of the JList are not of the correct type, you will get a
java.lang.ArrayStoreExceptionduring the arraycopy.