What is the fundamental difference between the Set<E>
and List<E>
interfaces?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
List:
Set:
Difference based on following points
1) Duplicity: List allows duplicate elements. Any number of duplicate elements can be inserted into the list without affecting the same existing values and their indexes. Set doesn’t allow duplicates. Set and all of the classes which implements Set interface should have unique elements.
2) Null values: List allows any number of null values. Set allows single null value at most.
3) Order: List and all of its implementation classes maintains the insertion order. Set doesn’t maintain any order; still few of its classes sort the elements in an order such as LinkedHashSet maintains the elements in insertion order.
As we are talking about the Java interfaces, why not look at the Javadoc ?!
List
is an ordered collection (sequence), which typically allows duplicatesSet
a is collection that contains no duplicate elements, iteration order may be guaranteed by the implementationThere is NO mention about lack of order concerning Sets: it depends on the implementation.
All of the
List
classes maintain the order of insertion. They use different implementations based on performance and other characteristics (e.g.ArrayList
for speed of access of a specific index,LinkedList
for simply maintaining order). Since there is no key, duplicates are allowed.The
Set
classes do not maintain insertion order. They may optionally impose a specific order (as withSortedSet
), but typically have an implementation-defined order based on some hash function (as withHashSet
). SinceSet
s are accessed by key, duplicates are not allowed.List:
List allows duplicate elements and null values. Easy to search using the corresponding index of the elements and also it will display elements in insertion order. Example:(linkedlist)
Output:
1
1
555
333
888
555
null
null
Value:1
Value:555
Value:333
Value:888
Value:555
Value:null
Value:null
Set:
Set isn't allow any duplicate elements and it allow single null value.It will not maintain any order to display elements.Only
TreeSet
will display in ascending order.Example:(TreeSet)
Output:
all
hello
welcome
world
java.lang.NullPointerException
Set doesn't allow null value and duplicate value
List Vs Set
1) Set does not allow duplicates. List allows duplicate. Based on the implementation of Set, It also maintains the insertion Order .
eg :
LinkedHashSet
. It maintains the insertion order.Please refer click here2) contains method. By nature of the Set it will give better performance to access. Best case its o(1). But List has performance issue to invoke
contains
.