gpt4 book ai didi

java - 初始化大型整数列表的最快方法是什么?

转载 作者:行者123 更新时间:2023-12-01 07:05:51 25 4
gpt4 key购买 nike

我需要用大量整数值预先填充一个列表。

除了迭代之外,还有更快的方法吗?

当前代码:

class VlanManager {
Queue<Integer> queue = Lists.newLinkedList();

public VlanManager(){
for (int i = 1; i < 4094; i++) {
queue.add(i);
}
}

此代码位于经常创建的类的构造函数中,因此我希望它尽可能高效(读取:性能而不是代码行)

最佳答案

4094 并不是很多要循环的项目,但如果它被频繁调用,您可能会考虑使用静态变量执行某些操作。

private static Integer[] theList;

static {
theList = new Integer[4094];
for (int i = 1; i < 4094; i++) {
theList[i-1] = i;
}
}

然后将该列表设为List

Queue<Integer> intQue = new LinkedList(Arrays.asList(theList));
<小时/>

如果您有可变对象列表,则使用此方法存在危险。这是可能发生的情况的示例。 整数是不可变的,因此这实际上并不适用于您的问题

class MyMutableObject {
public int theValue;
}

class Test {

private static MyMutableObject[] theList;

static {
theList = new MyMutableObject[4094];
for (int i = 1; i <= 4094; i++) {
theList[i-1] = new MyMutableObject();
theList[i-1].theValue = i;
}
}

public static void main(String [] args) {
Queue<MyMutableObject> que = new LinkedList(Arrays.asList(theList));
System.out.println(que.peek().theValue); // 1
// your actually modifing the same object as the one in your static list
que.peek().theValue = -100;
Queue<MyMutableObject> que2 = new LinkedList(Arrays.asList(theList));
System.out.println(que2.peek().theValue); // -100
}
}
<小时/>

@Bohemian 在使用静态列表而不是数组方面有一些优点,虽然性能提升非常小,但仍然是性能提升。另外,因为“数组”实际上只用作 List 而不是数组,所以应该这样声明。

private static List<Integer> theList;

static {
theList = new ArrayList(4094);
for (Integer i = 0; i < 4094; i++) {
theList.add(i+1);
}
}

关于java - 初始化大型整数列表的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24845767/

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