Java Collection - Difference between List and Set interfaces
Published April 11, 2022List and Set are both Java interfaces for extending the Collection Interface. We will examine the key differences between them in this post as well as when to use them.
Differences between the Set and List interfaces in Java
We will examine the key differences between List and Set interfaces based on the following key factors:
Implementation
Lists are implemented by ArrayLists, whereas HashSets implement sets.
Indexing
You can use ListIterator to traverse a List both forwards and backwards, but not a Set. Instead, use Iterator (which works on both Lists and Sets).
Ordering
Sets maintain order as opposed to Lists, which are unordered collections and do not maintain any order. A list is an ordered collection, which means the elements in the list are displayed in the same order they were inserted, so when the list content is displayed, it will be displayed the same way.
Null Object
The Lists does not have any restriction, and it supports adding null values, while on the other hand, the sets do not allow null values.
Duplicates
Lists can contain duplicates, but sets do not. A set does not allow duplicate elements since all its elements should be unique. If you insert a duplicate element into a set, the existing value would be overwritten.
When should you use a Set and a List?
Set is your best choice when you simply need to store unique values since it only stores unique values. However, if you want to maintain the insertion order despite duplication, List is your best choice.
Examples of a Set and a List
Example of a Set
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class ListExample { public static void main(String[] args) { List<String> al = new ArrayList<String>(); al.add("Rohit"); al.add("Panjab"); al.add("Kamir"); System.out.println("My ArrayList Items: "); System.out.print(al); List<String> ll = new LinkedList<String>(); ll.add("Shobit"); ll.add("Raul"); ll.add("Ketel"); System.out.println("\n My LinkedList Items: "); System.out.print(ll); } } |
Example of a List
import java.util.HashSet; import java.util.Set; import java.util.TreeSet; public class SetExample { public static void main(String[] args) { int myList[] = {60, 70, 80, 40 }; Set<Integer> dispSet = new HashSet<Integer>(); try{ for(int i = 0; i<4; i++){ dispSet.add(myList[i]); } System.out.println(dispSet); TreeSet<Integer> treeset = new TreeSet<Integer>(dispSet); System.out.println("Sorting in Asceding order:"); System.out.println(treeset); } catch(Exception e){ e.printStackTrace(); } } } |
Keywords: List interface, Set interface
Article Contributed By :
|
|
|
|
287 Views |