I want to know when to use Set and List.On which basis it should be decided.For example, when we are dealing with order application, at that what should I use? List any = new ArrayList<>(); or Set any = new HashSet(); or LinkedList.
-
4Quite a few questions around deal with this. Take a look e.g. at http://stackoverflow.com/questions/1035008/what-is-the-difference-between-set-and-list, http://stackoverflow.com/questions/322715/when-to-use-linkedlist-over-arraylist – lrnzcig Aug 20 '16 at 13:36
-
http://stackoverflow.com/a/21974362/1545775 – Maciej Marczuk Aug 20 '16 at 13:37
1 Answers
It all depends upon your current requirements
for example, consider some important points about
If you want to access the elements in the same way you're inserting them, then you should use
List
becauseList
is an ordered collection of elements. You can access them usingget(int index)
method, whereas no such method is available forSet
. The order in which they will be stored is not guaranteed.If your elements contains duplicates, then use
List
becauseSet
doesn't allow duplicates whereas if your elements are unique, then you can useSet
.As far as
LinkedList
andArrayList
are considered:LinkedList
are slow because they allow only sequential access. But they're good if your elements size is regularly changing, whereas if the size of your elements is fixed, then you should useArrayList
because they allow fast random read access, so you can grab any element in constant time.- However,
ArrayList
are not good when you require large delete operations because adding or removing from anywhere but the end requires shifting all the latter elements over. ArrayList
are not considered good when you have to insert anything in middle because if you want to insert a new element in the middle (and keep all the elements in the same order) then you're going to have to shift everything after that spot where element was inserted, whereas such operation inLinkedList
requires only change of some references.
Take a look at the features of several data structures and according to your requirements, you can decide where you should use which data structure.
also see:
- When to use LinkedList over ArrayList?
- What is the difference between Set and List?
- What Java Collection should I use?
- Insertion in the middle of ArrayList vs LinkedList

- 1
- 1

- 30,180
- 9
- 58
- 71