gpt4 book ai didi

java - "supplementary private method"如何帮助避免原始类型?

转载 作者:行者123 更新时间:2023-12-03 10:04:11 26 4
gpt4 key购买 nike

java.util.Collection的源代码中有一个函数叫做 shuffle :

@SuppressWarnings({"rawtypes", "unchecked"})
public static void shuffle(List<?> list, Random rnd) {
int size = list.size();
if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
for (int i=size; i>1; i--)
swap(list, i-1, rnd.nextInt(i));
} else {
Object arr[] = list.toArray();

// Shuffle array
for (int i=size; i>1; i--)
swap(arr, i-1, rnd.nextInt(i));

// Dump array back into list
// instead of using a raw type here, it's possible to capture
// the wildcard but it will require a call to a supplementary
// private method
ListIterator it = list.listIterator();
for (int i=0; i<arr.length; i++) {
it.next();
it.set(arr[i]);
}
}
}
代码中的注释说:“这里不使用原始类型,而是可以捕获通配符,但需要调用补充私有(private)方法。”
这意味着什么?没有原始类型怎么能写出来?

最佳答案

有一个page在 Oracle Docs 中解释了“捕获通配符”的含义。
shuffle 的情况下,您将“转储数组”操作提取到通用辅助方法中:

private static <T> void dumpArray(Object[] arr, List<T> list) {
ListIterator<T> it = list.listIterator();
for (int i=0; i<arr.length; i++) {
it.next();
it.set((T)arr[i]);
}
}

//...
dumpArray(arr, list);
这是有效的,因为正如文档所说:

Thanks to the helper method, the compiler uses inference to determine that T is CAP#1, the capture variable, in the invocation.

关于java - "supplementary private method"如何帮助避免原始类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63715953/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com