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
Ordered lists of element (unique or not)
Conform to Java's interface named
List
Can be accessed by index
implemetented using
Lists of unique elements:
Conform to Java's interface named
Set
Can not be accessed by index
implemetented using
Both interfaces
Set
andList
conform to Java's interface namedCollection
Set<E>
andList<E>
are both used to store elements of typeE
. The difference is thatSet
is stored in unordered way and does not allow duplicate values.List
is used to store elements in ordered way and it does allow duplicate values.Set
elements cannot be accessed by an index position, andList
elements can be accessed with an index position.Like the answer as SET don't have duplicate value and List can. Of course, order is another one thing to different them apart.
Conceptually we usually refer to an unordered grouping that allows duplicates as a Bag and doesn't allow duplicates is a Set.
Duplicity
Set doesn’t allow duplicates. Set and all of the classes which implements Set interface should have unique elements. List allows duplicate elements. Any number of duplicate elements can be inserted into the list without affecting the same existing values and their indexes.
Null values
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 and TreeSet(the elements maintain the ascending order by default)
class implementations
Here ist a clear example with groovy. i create a set and a list. then i try to store 20 randomly generated value within each list. the generated value can be in range 0 to 5
The result :
random Numbers:
4, 1, 4, 0, 1, 2, 4, 0, 0, 3, 4, 3, 2, 0, 4, 0, 1, 3, 1, 3
Set :
[4, 1, 0, 2, 3]
list :
[4, 1, 4, 0, 1, 2, 4, 0, 0, 3, 4, 3, 2, 0, 4, 0, 1, 3, 1, 3]
You can see that the difference is that: