509

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

JJJ
  • 32,902
  • 20
  • 89
  • 102
Johanna
  • 27,036
  • 42
  • 89
  • 117
  • 1
    See also http://stackoverflow.com/questions/769731/why-doesnt-java-util-set-have-getint-index. – Michael Myers Jun 23 '09 at 20:35
  • 5
    And if you want to find out in terms of performance , have a look at this question http://stackoverflow.com/questions/10799417/performance-and-memory-allocation-comparision-between-list-and-set – vsingh May 31 '13 at 15:07

26 Answers26

569

List is an ordered sequence of elements whereas Set is a distinct list of elements which is unordered (thank you, Quinn Taylor).

List<E>:

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Set<E>:

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

Community
  • 1
  • 1
Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
  • 8
    For a SortedSet, there are no two elements where compareTo() == 0, as equals is not called. – Peter Lawrey Jun 25 '09 at 17:52
  • 39
    A Set CAN be ordered, so the first statement of this answer is misleading, even if of course a List must be choosen to enforce the Collection order – Samuel EUSTACHI Mar 06 '13 at 11:00
  • 30
    WRONG! A Java set can be ordered, depending on the implementation; for example, a Java TreeSet is ordered. In the context of Java, the only difference between a List and a Set is that the Set contains unique items. In the context of mathematics, the items of a set are unique and unordered. – stackoverflowuser2010 Oct 19 '13 at 00:21
  • 54
    Yes, a Java Set CAN be BUT is not NECESSARILY ordered. Yes, if you have a TreeSet, you can count on that being ordered. But you have to KNOW that you have a TreeSet and not just a Set. If you are returned a Set, you can't depend on that to be ordered. A List on the other hand is ordered by its very nature and any implementation of List must be ordered. So, on the terms of the interface definition, it is not particularly wrong to say that a Set is unordered, but it's maybe a little more technically correct to say that a Set provides no guarantee of element order. – Spanky Quigman Nov 20 '13 at 22:28
  • 3
    It is wrong to say that a Set (in Java) is un-ordered because that is "guaranteeing" that the collection has no order. If all you know about a collection is that its elements are ordered, you cannot distinguish whether that collection is a Set or a List. By saying Set is un-ordered, it is implying that a collection of ordered elements cannot be a Set, which is not true. – FGreg Dec 02 '13 at 15:47
  • 17
    Don't conflate "ordered" with "sorted." Likewise, don't conflate the contract of an interface and implementations of the interface. It is also wrong to say that something which is "unordered" has no order, it simply means there are no guarantees about the implementation of the order (and that the order may not be stable between calls, unlike with an ordered list). – lilbyrdie Apr 10 '14 at 15:35
  • @stackoverflowuser2010 : What is the implementation difference between Java TreeSet (which is both ordered and unique) and C++ STL Set (which is only unique)? – Vinay May 27 '14 at 06:36
  • 1
    For anyone wondering how List is ordered, it is not sort order such as increasing or decreasing, the order is not by value of any of the elements in the list, so what does ordered mean? The insertion, the order in which elements where inserted. – Murali VP May 10 '15 at 15:27
  • Playing the devil's advocate here, but if you wanna claim that "a set can be ordered" you could also claim that it's wrong to say a list IS ordered, because that too depends on the implementation. I think this is a silly way to reason. An interface is decoupled from the implementation, the interface just defines a contract. With this reasoning we could say "Well, Serializeable doesn't really mean a class can be serialized, it depends, maybe the implementation just throws an exception?" What use is this? – sara Nov 30 '15 at 15:34
  • Set cant have null element. As mentioned in the answer "at most one null element" is wrong. – user2256009 Feb 15 '16 at 15:09
287
List Set
Duplicates Yes No
Order Ordered Depends on implementation
Position Access Yes No
Sergii Shevchyk
  • 38,716
  • 12
  • 50
  • 61
  • 4
    One thing to note: positional access performance depends a lot on the underlying implementation, array vs linked list http://stackoverflow.com/questions/322715/when-to-use-linkedlist-over-arraylist – Christophe Roussy Nov 30 '15 at 16:35
  • 2
    How are Sets indexed if not by positional access? (+1 for the ASCII-table) – tplive Sep 13 '18 at 17:56
  • I don't like to read. This makes it very concise and simple. – Rishav Feb 02 '22 at 14:51
84

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

Implemented using

  • LinkedList
  • ArrayList

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

Implemented 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

Chris Ballance
  • 33,810
  • 26
  • 104
  • 151
ivan_ivanovich_ivanoff
  • 19,113
  • 27
  • 81
  • 100
35

A Set cannot contain duplicate elements while a List can. A List (in Java) also implies order.

Peter
  • 6,354
  • 1
  • 31
  • 29
19
  • 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.

Hardwareguy
  • 2,941
  • 1
  • 17
  • 13
13

List:

Lists generally allow duplicate objects. Lists must be ordered, and are therefore accessible by index.

Implementation classes include: ArrayList, LinkedList, Vector

Set:

Sets do not allow duplicate objects. Most implementations are unordered, but it is implementation specific.

Implementation classes include: HashSet (unordered), LinkedHashSet (ordered), TreeSet (ordered by natural order or by provided comparator)

glen3b
  • 693
  • 1
  • 8
  • 22
csds
  • 131
  • 1
  • 2
12

List

  1. Is an Ordered grouping of elements.
  2. List is used to collection of elements with duplicates.
  3. New methods are defined inside List interface.

Set

  1. Is an Unordered grouping of elements.
  2. Set is used to collection of elements without duplicates.
  3. No new methods are defined inside Set interface, so we have to use Collection interface methods only with Set subclasses.
9

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)

import java.util.*;

public class ListExample {

 public static void main(String[] args) {
    // TODO Auto-generated method stub

    List<Integer> l=new LinkedList<Integer>();
    l.add(001);
    l.add(555);
    l.add(333);
    l.add(888);
    l.add(555);
    l.add(null);
    l.add(null);

    Iterator<Integer> il=l.iterator();

    System.out.println(l.get(0));

    while(il.hasNext()){
        System.out.println(il.next());
    }

    for(Integer str : l){
        System.out.println("Value:"+str);
    }
 }

}

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)

import java.util.TreeSet;

public class SetExample {

 public static void main(String[] args) {
    // TODO Auto-generated method stub

    TreeSet<String> set = new TreeSet<String>();
    try {
        set.add("hello");
        set.add("world");
        set.add("welcome");
        set.add("all");

        for (String num : set) {
            System.out.println( num);

        }
        set.add(null);
    } catch (NullPointerException e) {
        System.out.println(e);
        System.out.println("Set doesn't allow null value and duplicate value");
    }

 }

}

Output:

all
hello
welcome
world
java.lang.NullPointerException
Set doesn't allow null value and duplicate value

Newbie
  • 1,403
  • 2
  • 13
  • 22
Indhu
  • 109
  • 1
  • 2
8

As we are talking about the Java interfaces, why not look at the Javadoc ?!

  • A List is an ordered collection (sequence), which typically allows duplicates
  • A Set a is collection that contains no duplicate elements, iteration order may be guaranteed by the implementation

There is NO mention about lack of order concerning Sets: it depends on the implementation.

Christophe Roussy
  • 16,299
  • 4
  • 85
  • 85
  • 2
    Correct. LinkedHashSet contains elements in insertion order. – ggb667 Dec 02 '13 at 15:03
  • It's an interface, EVERYTHING depends on the implementation. List.get() could create a file containing the first 5 decimals of pi and throw a StackOverFlowException in some implementations, this does not imply that you can say "A list is something that can create files", since that is not part of the contract defined by the interface. The docs claim Set is modeled after the mathematical concept of a set, which by definition is un-ordered. Given a set in your code you cannot assume it is ordered without violating SOLID principles. – sara Nov 30 '15 at 15:38
  • @kai, I usually keep `LinkedHashSet` on the left-hand side if the code relies on the ordering later on. I only use `Set` if I really use it like one, as you cannot assume that the underlying implementation is a `LinkedHashSet` or such, it may be today, but tomorrow the code changes and it will fail. – Christophe Roussy Nov 30 '15 at 16:44
  • If you declare a LinkedHashSet you are not dealing with a Set, so making claims about how Sets should behave is hardly relevant. I'd say attributing (possible) orderedness to sets based on some implementations is akin to saying "Instances of Runnable have a run method meant to be run on some thread. Also they open a DB connection and read customer data depending on the implementation." Of course some implementations may do that, but that is not what is implied by the Runnable Interface. – sara Dec 01 '15 at 08:28
8
Factor List Set
Is ordered grouping elements? YES NO
Provides positional access by index? YES NO
Can store duplicate elements? YES NO
Can store multiple null elements? YES NO
Childs: ArrayList, LinkedList, Vector, and Stack HashSet and LinkedHashSet
Ahmed Nabil
  • 17,392
  • 11
  • 61
  • 88
8

List and Set both are interfaces. They both extends Collection interface. The important differences between set and list are:

  1. Duplicate Objects

The main difference between List and Set is that List allows duplicates while Set doesn't allow duplicates.

  1. Order

List is an ordered collection it maintains the insertion order, which means upon displaying the list content it will display the elements in the same order in which they got inserted into the list.

Set is an unordered collection, it doesn’t maintain any order. There are few implementations of Set which maintains the order such as LinkedHashSet (It maintains the elements in insertion order).

  1. Null elements

List allows any number of null elements. Set can have only a single null elements at most.

Ousama
  • 2,176
  • 3
  • 21
  • 26
6

A set is an unordered group of distinct objects — no duplicate objects are allowed. It is generally implemented using the hash code of the objects being inserted. (Specific implementations may add ordering, but the Set interface itself does not.)

A list is an ordered group of objects which may contain duplicates. It could be implemented with an ArrayList, LinkedList, etc.

Kasun Siyambalapitiya
  • 3,956
  • 8
  • 38
  • 58
Quinn Taylor
  • 44,553
  • 16
  • 113
  • 131
  • 1
    I am confused ! What does ordered/unordered means in this context? Is it related to ascending order and descending order? If so, `List` is not ordered – malhobayyeb Jan 11 '17 at 18:38
  • 5
    **Ordered** is when the input data are arranged exactly as inputted by the user whereas **Sorted** is when the input data is sorted lexicographically or ascending/descending order(in terms of integer values). **Unordered** means that the input data may or maynot be stored in the user inputted order. – Akhil Mar 22 '17 at 08:33
5

This might not be the answer you're looking for, but the JavaDoc of the collections classes is actually pretty descriptive. Copy/pasted:

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

Jeroen van Bergen
  • 1,046
  • 6
  • 7
3

Few note worthy differences between List and Set in Java are given as following :

1) Fundamental difference between List and Set in Java is allowing duplicate elements. List in Java allows duplicates while Set doesn't allow any duplicate. If you insert duplicate in Set it will replace the older value. Any implementation of Set in Java will only contains unique elements.

2) Another significant difference between List and Set in Java is order. List is an Ordered Collection while Set is an unordered Collection. List maintains insertion order of elements, means any element which is inserted before will go on lower index than any element which is inserted after. Set in Java doesn't maintain any order. Though Set provide another alternative called SortedSet which can store Set elements in specific Sorting order defined by Comparable and Comparator methods of Objects stored in Set.

3) Popular implementation of List interface in Java includes ArrayList, Vector and LinkedList. While popular implementation of Set interface includes HashSet, TreeSet and LinkedHashSet.

Its pretty clear that if you need to maintain insertion order or object and you collection can contain duplicates than List is a way to go. On the other hand if your requirement is to maintain unique collection without any duplicates than Set is the way to go.

Vibha Sanskrityayan
  • 1,905
  • 1
  • 16
  • 11
  • 1
    Hi @Vibha, If I wan the both condition? I means I do not want my data contain duplicates, and I also want it be order. – Panadol Chong Oct 31 '17 at 11:00
3

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 here

2) 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.

Siva Kumar
  • 1,983
  • 3
  • 14
  • 26
3

1.List allows duplicate values and set does'nt allow duplicates

2.List maintains the order in which you inserted elements in to the list Set does'nt maintain order. 3.List is an ordered sequence of elements whereas Set is a distinct list of elements which is unordered.

Rakesh
  • 31
  • 1
2

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 with SortedSet), but typically have an implementation-defined order based on some hash function (as with HashSet). Since Sets are accessed by key, duplicates are not allowed.

lavinio
  • 23,931
  • 5
  • 55
  • 71
  • Maps store objects by key, but sets store objects using a unique value related to the object, usually its hash code. (Maps may also use hash codes to check for key uniqueness, but they are not required to.) – Quinn Taylor Jun 24 '09 at 06:45
2

The biggest different is the basic concept.

From the Set and List interface. Set is mathematics concept. Set method extends collection.however not add new method. size() means cardinality(more is BitSet.cardinality, Linear counter,Log Log,HyperLogLog). addAll() means union. retainAll() means intersection. removeAll() means difference.

However List lack of these concepts. List add a lot of method to support sequence concept which Collection interface not supply. core concept is INDEX. like add(index,element),get(index),search(indexOf()),remove(index) element. List also provide "Collection View" subList. Set do not have view. do not have positional access. List also provide a lot of algorithms in Collections class. sort(List),binarySearch(List),reverse(List),shuffle(List),fill(List). the method params is List interface. duplicate elements are just the result of concepts. not the essential difference.

So the essential difference is concept. Set is mathematics set concept.List is sequence concept.

LiLi
  • 391
  • 3
  • 11
1

Ordering... a list has an order, a set does not.

Ricardo Marimon
  • 10,339
  • 9
  • 52
  • 59
1

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.

Steve Czetty
  • 6,147
  • 9
  • 39
  • 48
saibhushan
  • 27
  • 1
  • 1
    @BalusC please do not comment with out seeing the post date. See the post worthy at that time. – Yash Oct 30 '18 at 07:08
1

List:

  1. Allowed duplicates.
  2. Ordered in grouping elements.(In other words having definite order.No need to sorted in ascending order)

Set:

  1. Not allowed duplicates.
  2. Unordered in grouping elements.(In other words having no definite order.It might or might not arranged in ascending order )
ChrisF
  • 134,786
  • 31
  • 255
  • 325
1

Set: A Set cannot have Duplicate elements in its collections. it is also an unordered collection. To access the data from Set, it is required to use Iterator only and index based retrieve is not possible for it. It is mainly used whenever required uniqueness collection.

List: A List can have duplicate elements, with the natural ordered as it is inserted. Thus, it can be retrieved data based on index or iterator. It is widely used to store collection which needs to access based on index.

Arvind Chavhan
  • 488
  • 1
  • 6
  • 14
0

Hi So many answers are already given..Let me point out some points which are not mentioned so far:

  • Most of the List implementations (ArrayList,Vector) implement RandomAccess interface which is a marker interface for faster access. None of the Set implementations do that.
  • List uses one special Iterator called ListIterator which supports iteration in both directions. Set uses Iterator which supports only 1 way iteration
  • HashSet takes 5.5 times more memory than ArrayList for storing same number of elements.
smruti ranjan
  • 741
  • 2
  • 9
  • 23
  • @smurti this is a bit late, and am not sure whether you have noted, but your first point contradicts itself: "Most of the List implementations (ArrayList,Vector) implement RandomAccess..." and "...None of the List implementations do that" – Peter Feb 09 '19 at 07:02
-1

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.
justice
  • 306
  • 2
  • 12
-1

TOPIC Name: List VS Set

I have just gone through Java's most important topic called Collections Framework. I thought to share my little knowledge about Collections with you. List, Set, Map are the most important topic of it. So let's start with List and Set.

Difference between List and Set:

  1. List is a collection class which extends AbstractList class where as Set is a collection class which extends AbstractSet class but both implements Collection interface.

  2. List interface allows duplicate values (elements) whereas Set interface does not allow duplicate values. In case of duplicate elements in Set, it replaces older values.

  3. List interface allows NULL values where as Set interface does not allow Null values. In case of using Null values in Set it gives NullPointerException.

  4. List interface maintains insertion order. That means the way we add the elements in the List in the same way we obtain it using iterator or for-each style. Whereas Set implementations do not necessarily maintain insertion order. (Although SortedSet does using TreeSet, and LinkedHashSet maintains insertion order).

  5. List interface has its own methods defined whereas Set interface does not have its own method so Set uses Collection interface methods only.

  6. List interface has one legacy class called Vector whereas Set interface does not have any legacy class

  7. Last but not the least... The listIterator() method can only be used to cycle through the elements within List Classes whereas we can use iterator() method to access Set class elements

Anything else can we add? Please let me know.

Thanks.

glen3b
  • 693
  • 1
  • 8
  • 22
  • For one, `List` and `Set` are interfaces which also have "base" implementations in the form of an abstract class (which you mentioned). Also, #3 is **completely inaccurate**, as most sets allow null values (but implementation dependent). I don't understand #5 and #7, and for #6 `Vector` is not legacy, but is just synchronized and not preferred for use except when synchronization is needed. – glen3b Jun 16 '14 at 18:14
-3

Set:

Cannot have duplicate values Ordering depends on implementation. By default it is not ordered Cannot have access by index

List:

Can have duplicate values Ordered by default Can have access by index