【发布时间】:2021-05-12 14:06:31
【问题描述】:
我想要一个由 n 组整数组成的列表,最初这个列表应该用 null 填充。 很多 Set 稍后会被初始化,有些会保持为空。
我尝试了不同的方法来实现这一点,其中一些包括在这里:
List<HashSet<Integer>> List_of_Sets = Arrays.asList(new HashSet[n]);
ArrayList<HashSet<Integer>> List_of_Sets = new ArrayList<>(n);
while(n-- > 0) List_of_Sets.add(null);
有更快的方法吗?
为了澄清数组的一个例子是 Arrays.fill() 曾经比:
/*
* initialize a smaller piece of the array and use the System.arraycopy
* call to fill in the rest of the array in an expanding binary fashion
*/
public static void bytefill(byte[] array, byte value) {
int len = array.length;
if (len > 0){
array[0] = value;
}
//Value of i will be [1, 2, 4, 8, 16, 32, ..., len]
for (int i = 1; i < len; i += i) {
System.arraycopy(array, 0, array, i, ((len - i) < i) ? (len - i) : i);
}
}
^以上代码来自罗斯·德鲁对Fastest way to set all values of an array?的回答
【问题讨论】:
-
1) 答案是否定的 (AFAIK)。 2)您应该能够通过基准测试(使用正确的技术!!)检查哪个替代方案最快,但我认为
Arrays.asList版本应该稍微快一些。 3)这是“过早的优化”吗? -
最后,如果速度对您来说真的很重要,您可以将
ArrayList替换为数组。这将更快,无论是创建和访问/更新。 (只是在某些情况下不太方便。)据我所知,您不会使用ListAPI 添加和删除列表元素的能力...... -
Collections.fill()不会在空列表上做任何事情,所以如果您对它感到满意,那就有点令人费解了。有Collections.nCopies()可以与null一起使用。 -
我会
List<HashSet<Integer>> List_of_Sets = Arrays.asList(new HashSet[n]);继续前进 -
你也可以写一个
native方法。
标签: java performance arraylist