有如下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[]?
return set.toArray(arr1);
toArray()
The method is also generic, and the return type is consistent with the parameter type. Yours is anObject
array, of course it won’t work.