标题说明了一切。我必须将数千个对象添加到列表中,然后对它们进行排序。现在我想(因为向 LinkedList 添加东西要快得多)我会使用 LinkedList 来创建,然后像这样创建一个新的 ArrayList:
LinkedList<Foo> createList = new LinkedList<Foo>();
// add stuff
ArrayList<Foo> returnList = new ArrayList<Foo>(createList);
Collections.sort(returnList);
return returnList;
我的问题是:
这种方法真的比直接将对象添加到 ArrayList 更快甚至更慢吗?
或者,我知道要添加的对象的粗略数量。具有初始容量的 ArrayList 是否更快?
最佳答案
这与两个问题有关:
1. ArrayList
有什么区别和 LinkedList
,哪个插入速度更快?
2. 哪个排序更快?
对于问题1,ArrayList
的本质区别和 LinkedList
是数据结构。 ArrayList
在内部使用数组并且擅长随机访问(O(1))。另一方面,LinkedList
擅长删除和插入项目(O(1)。你可以找到更多here
回到问题,因为我们这里不需要按索引插入。
所以ArrayList
和 LinkedList
都是 O(1) 操作。但是LinkedList
会因为数据结构的原因造成更多的内存,而ArrayList
如果需要扩展容量会导致更多时间(设置足够大的初始容量将有助于加快插入速度)。
对于问题 2,您可以找到答案 hereArrayList
更适合排序。
总之,我认为你应该坚持使用ArrayList,不需要导入LinkedList
这里。
关于Java:创建 LinkedList 并将其转换为 ArrayList 进行排序是否有意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62227775/