search

Home  >  Q&A  >  body text

java泛型 - java数组泛型转换

有如下java代码:

// 求两个数组的并集,利用set的元素唯一性
    public static <T> T[] union(T[] arr1, T[] arr2) {
        Set<T> set = new HashSet<>();
        Collections.addAll(set, arr1);
        Collections.addAll(set, arr2);
        return set.toArray(new Object[set.size()]);
    }

问:该段代码报错,提示返回的类型应该是Object[],怎么才能返回T[]?

怪我咯怪我咯2803 days ago809

reply all(1)I'll reply

  • 阿神

    阿神2017-04-17 15:08:51

    return set.toArray(arr1);

    toArray()The method is also generic, and the return type is consistent with the parameter type. Yours is an Object array, of course it won’t work.

    reply
    0
  • Cancelreply