I'm running some benchmarks. One of my tests depends on order, so I'm using a TreeSet for that. My second test doesn't, so I'm using a HashSet for it.
I know that insertion is slower for the TreeSet. But what about iterating through all elements?
I'm running some benchmarks. One of my tests depends on order, so I'm using a TreeSet for that. My second test doesn't, so I'm using a HashSet for it.
I know that insertion is slower for the TreeSet. But what about iterating through all elements?
TreeSets
internally usesTreeMaps
which areRed Black Trees
(special type ofBST
) .BST
Inorder Traversal isO(n)
HashSets
internally usesHashMaps
which use anarray
for holding Entry objects.Here also traversal should be
O(n)
.Unless you write a benchmark it is going to be difficult to prove which is faster.
If you want stable ordering with (nearly) the performance of a
HashSet
, then use aLinkedHashSet
. You will still get constant-time operations, whereas I would assume aTreeSet
will get you logarithmic time.From a similar post (Hashset vs Treeset):
HashSet is much faster than TreeSet (constant-time versus log-time for most operations like add, remove and contains) but offers no ordering guarantees like TreeSet.
HashSet:
TreeSet:
first()
,last()
,headSet()
, andtailSet()
etcImportant points:
HashSet
andTreeSet
. Implemented as a hash table with a linked list running through it, however it provides insertion-ordered iteration which is not same as sorted traversal guaranteed by TreeSet.So choice of usage depends entirely on your needs but I feel that even if you need an ordered collection then you should still prefer HashSet to create the Set and then convert it into TreeSet.
Set<String> s = new TreeSet<String>(hashSet);