I want to know the comparison between List and Set in terms of performance,memory allocation and usability.
If i don't have any requirement of keeping the uniqueness in the list of objects, neither required the insertion order to be maintained, Can I use ArrayList and SortedSet/HashSet interchangeably? Will it be good to directly use Collections class instead of even list/set?
P.S. I also don't have any need for list or set specific functions provided by java. I am using List/Set instead of Array only because they can dynamically grow without extra programming efforts.
If you don't care about the ordering, and don't delete elements, then it really boils down to whether you need to find elements in this data structure, and how fast you need those lookups to be.
Finding an element by value in a
HashSet
isO(1)
. In anArrayList
, it'sO(n)
.If you are only using the container to store a bunch of unique objects, and iterate over them at the end (in any order), then arguably
ArrayList
is a better choice since it's simpler and more economical.HashSet
consumes about 5.5 times more memory thanArrayList
for the same number of elements (although they're both still linear), and has significantly slower iteration (albeit with the same asymptotics); a quick Google search suggests a 2-3x slowdown forHashSet
iteration versusArrayList
.If you don't care about uniqueness or the performance of
contains
, then useArrayList
.If you plan only to add elements and later iterate over them, your best bet is
ArrayList
as it's closest to the arrays you are replacing. It's more memory efficient thanLinkedList
or anySet
implementation, has fast insertion, iteration, and random access.Use
HashSet
if you need to use.contains(T)
frequently.Example:
If you will compare, searching between List and Set, Set will be better because of the underline Hashing algorithm.
In the case of a list, in worst case scenario, contains will search till the end. In case of Set, because of hashing and bucket, it will search only subset.
Sample use case: Add 1 to 100_000 integer to ArrayList and HashSet. Search each integer in ArrayList and HashSet.
Set will take 9 milliseconds where as List will take 16232 seconds.
If you don't have the requirement to have unique elements in collection simply use
ArrayList
unless you have very specific needs.If you have the requirement to have only unique elemets in collection, then use
HashSet
unless you have very specific needs.Concerning
SortedSet
(and it's implementorTreeSet
), as per JavaDoc:Meaning it's targeted at quite specific use cases, when elements should be always ordered in a
set
, which is not needed usually.