java泛型 - java数组泛型转换
怪我咯
怪我咯 2017-04-17 15:06:51
0
1
777

有如下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[]?

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(1)
阿神

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!