What is the difference between Set and List?

JavaListSet

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

List Set
Duplicates Yes No
Order Ordered Depends on implementation
Position Access Yes No

Solution 3 - Java

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

Solution 4 - Java

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

Solution 5 - Java

  • 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.

Solution 6 - Java

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)

Solution 7 - Java

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.

Solution 8 - Java

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

Solution 9 - Java

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.

Solution 10 - Java

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.

Solution 11 - Java

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.

Solution 12 - Java

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

Solution 13 - Java

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.

Solution 14 - Java

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.

Solution 15 - Java

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.

Solution 16 - Java

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

  1. 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.

Solution 17 - Java

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.

Solution 18 - Java

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.

Solution 19 - Java

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

Solution 20 - Java

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 )

Solution 21 - Java

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.

Solution 22 - Java

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.

Solution 23 - Java

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.

Solution 24 - Java

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.

Solution 25 - Java

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.

Solution 26 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohannaView Question on Stackoverflow
Solution 1 - JavaAndrew HareView Answer on Stackoverflow
Solution 2 - JavaSergii ShevchykView Answer on Stackoverflow
Solution 3 - Javaivan_ivanovich_ivanoffView Answer on Stackoverflow
Solution 4 - JavaPeterView Answer on Stackoverflow
Solution 5 - JavaHardwareguyView Answer on Stackoverflow
Solution 6 - JavacsdsView Answer on Stackoverflow
Solution 7 - JavaShankar SuligaviView Answer on Stackoverflow
Solution 8 - JavaIndhuView Answer on Stackoverflow
Solution 9 - JavaChristophe RoussyView Answer on Stackoverflow
Solution 10 - JavaQuinn TaylorView Answer on Stackoverflow
Solution 11 - JavaJeroen van BergenView Answer on Stackoverflow
Solution 12 - JavaMd. Samim hossainView Answer on Stackoverflow
Solution 13 - JavaOusamaView Answer on Stackoverflow
Solution 14 - JavaRakeshView Answer on Stackoverflow
Solution 15 - JavaVibha SanskrityayanView Answer on Stackoverflow
Solution 16 - JavaSiva KumarView Answer on Stackoverflow
Solution 17 - JavalavinioView Answer on Stackoverflow
Solution 18 - JavaLiLiView Answer on Stackoverflow
Solution 19 - JavaRicardo MarimonView Answer on Stackoverflow
Solution 20 - JavavijaybhupathiView Answer on Stackoverflow
Solution 21 - JavasaibhushanView Answer on Stackoverflow
Solution 22 - JavaArvind ChavhanView Answer on Stackoverflow
Solution 23 - Javasmruti ranjanView Answer on Stackoverflow
Solution 24 - JavajusticeView Answer on Stackoverflow
Solution 25 - Javauser3542872View Answer on Stackoverflow
Solution 26 - Javauser2142109View Answer on Stackoverflow