简体   繁体   English

有没有办法比 Java 中的 O(n) 更快地获取列表的最后一个元素?

[英]Is there a way to get the last element of a list faster than O(n) in Java?

I have the following code, where getIDs() returns a list of IDs:我有以下代码,其中getIDs()返回一个 ID 列表:

List<Long> ids = getIds();
Long neededID = ids.get(ids.size()-1);

Now sonarqube says:现在 sonarqube 说:

Collection methods with O(n) performance should be used carefully (java:S2250) The time complexity of method calls on collections is not always obvious.应谨慎使用具有 O(n) 性能的收集方法 (java:S2250) collections 上的方法调用的时间复杂度并不总是很明显。 For instance, for most collections the size() method takes constant time, but the time required to execute ConcurrentLinkedQueue.size() is O(n), ie directly proportional to the number of elements in the collection.例如,对于大多数 collections,size() 方法需要固定时间,但执行 ConcurrentLinkedQueue.size() 所需的时间为 O(n),即与集合中的元素数量成正比。 When the collection is large, this could therefore be an expensive operation.当集合很大时,这可能是一项昂贵的操作。 This rule raises an issue when the following O(n) methods are called outside of constructors on class fields:当在 class 字段的构造函数之外调用以下 O(n) 方法时,此规则会引发问题:

I did not find any public link to show you that rule.我没有找到任何公共链接向您展示该规则。

So in my understanding the rule says size() has a runtime of O(n) and I could get() an element of the list faster if I would know the last index.因此,在我的理解中,规则说size()的运行时间为 O(n),如果我知道最后一个索引,我可以更快地get()列表中的一个元素。 So my question is now if there is an way to get the last element of the list faster, without using size() .所以我现在的问题是,是否有一种方法可以在不使用size()的情况下更快地获取列表的最后一个元素。

I have already done some search but the only thing that I found if I search for get last element of list is that you can use list.get(list.size()-1) .我已经进行了一些搜索,但是如果我搜索获取列表的最后一个元素,我发现的唯一一件事就是您可以使用list.get(list.size()-1)

The answer to this question was that a LinkedList.getSize() only has a complexity of O(1).这个问题的答案是LinkedList.getSize()只有 O(1) 的复杂度。 So it was not relevant for me.所以这对我来说无关紧要。

list.get(list.size()-1) would always be O(n) because a linked list is not a random access data structure like a primitive array. list.get(list.size()-1)总是 O(n) 因为链表不是像原始数组那样的随机访问数据结构。 To retrieve a value of a given position in the list, you would have to traverse the list starting at the first node until you get to the node of the position you want.要在列表中检索给定 position 的值,您必须从第一个节点开始遍历列表,直到到达您想要的 position 的节点。 So, don't use list.get(index) to retrieve the last element.所以,不要使用list.get(index)来检索最后一个元素。 Many implementation maintain a reference to the last node in the list so that retrieving the last element is O(1).许多实现维护对列表中最后一个节点的引用,以便检索最后一个元素是 O(1)。 I don't have the code of java.util.LinkedList but I would imagine its method getLast() is O(1).我没有java.util.LinkedList的代码,但我想它的方法getLast()是 O(1)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM