我从我的 A
类返回一个列表。我想从列表中删除第一个元素并将其作为最后一个元素添加到同一列表中。我是这样做的。
myList.add(myList.get(0));
myList.remove(0);
目标硬件是 Android 操作系统。我应该以返回 ArrayList
或 LinkedList
的方式编写我的 A
类吗?对于以下场景哪个更好:
myList 始终有 100 个元素
myList 始终有 10 个元素
也许我看到了一个没有问题的地方。您是否认为在这种情况下我不应该关心性能,因为问题规模(对于 1 和 2)很小?
我知道“过早优化是万恶之源”这句话。这就是为什么我在更改我的实现之前犹豫不决(至于现在,我的 A
对象返回一个 ArrayList)。
简答 如果您经常添加/删除/更新元素,您应该选择 LinkedList
,尤其是对于第一个/最后一个元素的情况,因为它包含一个指针到第一个和最后一个节点
长答案 LinkedList
add 方法提供 O(1)
性能,而 ArrayList 提供 O(n)
最坏的情况。
LinkedList
更快。它只会引用节点,所以第一个消失:
此外,ArrayList
适用于一次写入多次读取或附加程序,但不擅长从前面或中间添加/删除。
例如,从链表中删除一个元素的成本为 O(1)
,而为数组(数组列表)删除一个元素的成本为 O(n)
。
但是,这并不总是一条规则,因为bigoh帖子状态:
Big-oh notation can give very good ideas about performance for large amounts of data, but the only real way to know for sure is to actually try it with large data sets. There may be performance issues that are not taken into account by big-oh notation, eg, the effect on paging as virtual memory usage grows. Although benchmarks are better, they aren't feasible during the design process, so Big-Oh complexity analysis is the choice.
以上内容已通过 this 验证post,其中 LinkedList
也被证明很慢。
最后,为了进一步/ future 引用,请根据 javaconceptoftheday.com 查看它们的用例比较。 :
引用资料
http://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html
http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html