Home » Java » What is the difference between Set and List?

What is the difference between Set and List?

Posted by: admin November 2, 2017 Leave a comment

Questions:

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

Answers:

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.

Questions:
Answers:
╔═══════════════════╦══════════════════════╦═════════════════════════════╗
║                   ║         List         ║            Set              ║
╠═══════════════════╬══════════════════════╬═════════════════════════════╣
║     Duplicates    ║          YES         ║            NO               ║
╠═══════════════════╬══════════════════════╬═════════════════════════════╣
║       Order       ║       ORDERED        ║  DEPENDS ON IMPLEMENTATION  ║
╠═══════════════════╬══════════════════════╬═════════════════════════════╣
║ Positional Access ║         YES          ║            NO               ║ 
╚═══════════════════╩══════════════════════╩═════════════════════════════╝

Questions:
Answers:

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

Questions:
Answers:

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

Questions:
Answers:
  • 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.

Questions:
Answers:

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.
Questions:
Answers:

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)

Questions:
Answers:

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.

Questions:
Answers:

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.

Questions:
Answers:

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.

Questions:
Answers:

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.

Questions:
Answers:

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

Questions:
Answers:

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.

Questions:
Answers:

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.

Questions:
Answers:

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.

Questions:
Answers:

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.

Questions:
Answers:

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 )
Questions:
Answers:

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 

Questions:
Answers:

List:
List is allow duplicate elements and null values.Easy for search elements using the corresponding index of the element 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

Questions:
Answers:

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.

Questions:
Answers:

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 List 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.
Questions:
Answers:

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.
Questions:
Answers:

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

Questions:
Answers:

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.

Questions:
Answers:

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.

Questions:
Answers:

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