由于 Java 类型擦除,您试图实现的目标不能直接在 Java 中完成。但是,有一些技巧几乎可以达到您的期望。
以下是两种解决方案(或多或少可以接受):
public static <U extends Collection<T>, T> U jListSelected2Coll(
    JList list, U coll, Class<T> type2) throws InstantiationException,
        IllegalAccessException {
    Object[] array = list.getSelectedValues();
    T[] dest = (T[]) Array.newInstance(type2, array.length);
    System.arraycopy(array, 0, dest, 0, array.length);
    Collections.addAll(coll, dest);
    return coll;
}
public static void test() throws InstantiationException, IllegalAccessException {
    JList list = new JList();
    TreeSet<String> treeSet = jListSelected2Coll(list, new TreeSet<String>(), String.class);
    // do something with the treeSet
}
第二种选择也“有效”,但不如第一种安全(因为你不能Class<U extends Collection<T>>用 Java 表达):
public static <U extends Collection<T>, T> U jListSelected2Coll(
    JList list, Class<U> collType, Class<T> type2) throws InstantiationException,
        IllegalAccessException {
            U coll = collType.newInstance();
    Object[] array = list.getSelectedValues();
    T[] dest = (T[]) Array.newInstance(type2, array.length);
    System.arraycopy(array, 0, dest, 0, array.length);
    Collections.addAll(coll, dest);
    return coll;
}
public static void test() throws InstantiationException, IllegalAccessException {
    JList list = new JList();
    TreeSet<String> treeSet = jListSelected2Coll(list, TreeSet.class, String.class);
    // do something with the treeSet
}
在这两种情况下,如果 JList 的选定值的类型不正确,您将java.lang.ArrayStoreException在 arraycopy 期间得到一个。