- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Set vs HashSet vs TreeSet in Java
A Set is a generic set of values with no duplicate elements. A TreeSet is a set where the elements are sorted.
A HashSet is a set where the elements are not sorted or ordered. It is faster than a TreeSet. The HashSet is an implementation of a Set.
Set is a parent interface of all set classes like TreeSet, HashSet, etc.
Example
import java.util.*; public class Demo { public static void main(String args[]) { int a[] = {77, 23, 4, 66, 99, 112, 45, 56, 39, 89}; Set<Integer> s = new HashSet<Integer>(); try { for(int i = 0; i < 5; i++) { s.add(a[i]); } System.out.println(s); TreeSet sorted = new TreeSet<Integer>(s); System.out.println("Sorted list = "); System.out.println(sorted); } catch(Exception e) {} } }
Output
[66, 99, 4, 23, 77] Sorted list = [4, 23, 66, 77, 99]
- Related Articles
- Convert HashSet to TreeSet in Java
- C++ vs Java vs Python?
- Cplus plus vs Java vs Python?
- Arrays vs Set in JavaScript.
- equals() vs == in Java
- Set vs Map in C++ STL
- Java String.equals vs ==
- Perl vs Java
- Scala vs Java
- set vs unordered_set in C++ STL(3)
- Inheritance in C++ vs Java
- Foreach in C++ vs Java
- Iterator vs ListIterator in Java?
- Abstraction vs Encapsulation in Java
- Iterator vs forEach in Java

Advertisements