Sunday, December 3, 2017

Set vs List: When to use Set instead of List?

A Set cannot contain duplicate elements while a List can. A List (in Java) also implies order. Conceptually we usually refer to an unordered grouping that allows duplicates as a Bag and doesn't allow duplicates is a Set. List is used for the collection of elements with duplicates.
For more, you can go through this link: What is the difference between Set and List?

When to use List, Set and Map in Java?

1) If you do not want to have duplicate values in the database then Set should be your first choice as all of its classes do not allow duplicates.
2) If there is a need for frequent search operations based on the index values then List (ArrayList) is a better choice.
3) If there is a need of maintaining the insertion order then also the List is a preferred collection interface.
4) If the requirement is to have the key & value mappings in the database then Map is your best bet.

No comments:

Post a Comment