

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference between List and Set in Java
List and Set both interface belongs to the Collection framework. Both interfaces extend the Collection interface. They both are used to store a collection of objects as a single unit.
Before jdk1.2, we used to use Arrays, Vectors, and Hashtable for grouping objects as a single unit.
Sr. No. | Key | List | Set |
---|---|---|---|
1 | Positional access | The list provides positional access of the elements in the collection. | Set doesn't provide positional access to the elements in the collection |
2 | Implementation | Implementation of List are ArrayList,LinkedList,Vector ,Stack | Implementation of a set interface is HashSet and LinkedHashSet |
3 | Duplicate | We can store the duplicate elements in the list. | We can’t store duplicate elements in Set |
4 | Ordering | List maintains insertion order of elements in the collection | Set doesn’t maintain any order |
5 | Null Element | The list can store multiple null elements | Set can store only one null element |
Example of List
import java.util.List; import java.util.ArrayList; import java.util.LinkedList; public class ListExample { public static void main(String[] args) { List<String> al = new ArrayList<String>(); al.add("BMW"); al.add("Audi"); al.add("BMW"); System.out.println("List Elements: "); System.out.print(al); } }
Output
List Elements: [BMW, Audi, BMW]
Example of Set
import java.util.Set; import java.util.HashSet; import java.util.TreeSet; public class SetExample { public static void main(String args[]) { int count[] = {2, 4, 3, 5}; Set<Integer> hset = new HashSet<Integer>(); try{ for(int i = 0; i<4; i++){ hset.add(count[i]); } System.out.println(hset); } catch(Exception e){ e.printStackTrace(); } } }
Output
[2, 4, 3, 5]
- Related Questions & Answers
- Difference between Tree Set and Hash Set in Java
- Difference Between List and ArrayList in Java
- Difference between Singly linked list and Doubly linked list in Java
- Difference between the list() and listFiles() methods in Java
- Difference Between Fuzzy Set and Crisp Set
- Difference between Set and MultiSet in C++
- Difference between Set and UnOrderSet in C++
- Difference Between Array and Linked List
- Difference between List and Tuples in Python.
- Difference Between List and Tuple in Python
- Difference between List and Array types in Kotlin
- Difference between Java and JavaScript.
- Difference between Go and Java.
- Difference Between C++ and Java
- Difference between a Static Queue and a Singly Linked List in Java.
Advertisements