What is the difference between Set and List?

2019-01-01 06:02发布

What is the fundamental difference between the Set<E> and List<E> interfaces?

标签: java list set
26条回答
长期被迫恋爱
2楼-- · 2019-01-01 06:31

Ordered lists of element (unique or not)
Conform to Java's interface named List
Can be accessed by index

implemetented using

  • LinkedList
  • ArrayList

Lists of unique elements:
Conform to Java's interface named Set
Can not be accessed by index

implemetented using

  • HashSet (unordered)
  • LinkedHashSet (ordered)
  • TreeSet (sorted by natural order or by provided comparator)

Both interfaces Set and List conform to Java's interface named Collection

查看更多
深知你不懂我心
3楼-- · 2019-01-01 06:31

Set<E> and List<E> are both used to store elements of type E. The difference is that Set 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, and List elements can be accessed with an index position.

查看更多
墨雨无痕
4楼-- · 2019-01-01 06:32

Like the answer as SET don't have duplicate value and List can. Of course, order is another one thing to different them apart.

查看更多
笑指拈花
5楼-- · 2019-01-01 06:34
  • A List is an ordered grouping of items
  • A Set is an unordered grouping of items with no duplicates allowed (usually)

Conceptually we usually refer to an unordered grouping that allows duplicates as a Bag and doesn't allow duplicates is a Set.

查看更多
大哥的爱人
6楼-- · 2019-01-01 06:35

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

List allows any number of null values.
Set allows single null value at most

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

List: ArrayList, LinkedList 
Set: HashSet, LinkedHashSet, TreeSet 
查看更多
梦寄多情
7楼-- · 2019-01-01 06:36

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

s = [] as Set
l = []

max = 5
print "random Numbers :"
20.times{
e = (int)Math.random()*max
s << e
l << e
print "$e, "
}


println "\n"
println "Set : $s "
println "list : $l

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:

  • Set does not allow duplicate values.
  • List allow duplicate values.
查看更多
登录 后发表回答