Reputation: 19347
If I make analogy to Oracle database : they have the notion of "index" and "hint" to speed the execution of a query. So I want to make the analogy to Java
: is it possible to make the execution of the "contains
" method of a collection
to be quick ?
Upvotes: 1
Views: 43
Reputation: 533660
is it possible to make the execution of the "contains" method of a collection to be quick ?
Yes, use a collection with a faster contains
method.
e.g.
HashSet -> O(1)
SortedSet -> O(ln N)
List -> O(N)
The big-O time complexity indicates how the worst case time for an operation as the size of the collection grows. Lower time complexity is faster for modest to large collections.
Note: this only tells you how the collection scales. If the collection is very small like 1 or 2, then a List might be the fastest.
The Big-O
notation is well explained What is a plain English explanation of "Big O" notation?
Upvotes: 4
Reputation: 7166
It depends on what do you want to do with that collection. These are the standard options:
HashSet
. Once you have this Set
set up, the contains()
method will run in O(constant) time.LinkedHashSet
. It is almost the same as the HashSet
, but it maintains a LinkedList
on the top of the Set so you can maintain the order of original insertion.contains()
method will return in O(log n) time which is still fairly quick.If none of these is good for you, then you can have your collection, assign another HashSet
and maintain them together. However, I'm afraid that the performance gain isn't justified at most of the cases.
Upvotes: 1