泛型数组 @SafeVarargs 怎么使用?

import java.util.Arrays;

public class Main {

public static void main(String[] args) {

String[] arr = asArray("one", "two", "three");

System.out.println(Arrays.toString(arr));

String[] firstTwo = pickTwo("one", "two", "three");

System.out.println(Arrays.toString(firstTwo));

}

static <K> K[] pickTwo(K k1, K k2, K k3) {

return asArray(k1, k2);

}

@SafeVarargs

static <T> T[] asArray(T... objs) {

return objs;

}

}

pickTwo报错: class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.String;

@SafeVarargs 怎么没效果呢?不是这样用的吗?


回答:

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

public class Main {

public static void main(String[] args) {

List<String> arr = asList("one", "two", "three");

System.out.println(arr);

List<String> firstTwo = pickTwo("one", "two", "three");

System.out.println(firstTwo);

}

static <K> List<K> pickTwo(K k1, K k2, K k3) {

return asList(k1, k2);

}

@SafeVarargs

static <T> List<T> asList(T... objs) {

return new ArrayList<>(Arrays.asList(objs));

}

}

以上是 泛型数组 @SafeVarargs 怎么使用? 的全部内容, 来源链接: utcz.com/p/945366.html

回到顶部