Thursday, June 11, 2020

Difference between List and Set Interfaces



List and Set both are interfaces. They both extends Collection interface.However, there are some differences between the both which are listed below:



ListSet
The List can contain duplicate elementsSet includes unique items means it cannot contains duplicates. All the elements of a Set should be unique if you try to insert the duplicate element in Set it would replace the existing value.
The List is an ordered collection which maintains the insertion order, which means upon displaying the list of content it will display the elements in the same order in which they got inserted into the list.Set is an unordered collection which does not preserve the insertion order. There are few implementations of Set which maintains the order such as LinkedHashSet (It maintains the elements in insertion order).
The List interface contains a single legacy class which is Vector classSet interface does not have any legacy class.
The List interface can allow n number of null valuesSet interface only allows a single null value.
List implementations are like ArrayList, LinkedList,Vector,Stack etc.Set implementations are like HashSet,LinkedHashSet,TreeSet
ListIterator can be used to traverse a List in both the directions(forward and backward)ListIterator can not be used to traverse a Set. We can use Iterator (It works with List too) to traverse a Set.


Based on the requirement we prefer to use List or Set interfaces at times.

List: If there is a need to maintain the insertion order irrespective of the duplicate elements then List is a best preference. ArrayList and LinkedList both  of the implementations of List interface sorts the elements in their insertion order.

Set: If the requirement is to have only unique values then Set is your best preference as any implementation of Set maintains unique values only.

No comments:

Post a Comment

Hello Buddy, if you have any doubts or need any clarification , feel free to comment. Thanks.