If you were to use a set, how would you determine between a HashSet and a TreeSet?
Answers
Answer:
HashSet offers constant time cost while TreeSet offers log(n) time cost for such operations. 2) HashSet does not maintain any order of elements while TreeSet elements are sorted in ascending order by default.
Explanation:
please mark my ans as brainliest please
Answer:
1) HashSet gives better performance (faster) than TreeSet for the operations like add, remove, contains, size etc. HashSet offers constant time cost while TreeSet offers log(n) time cost for such operations.
2) HashSet does not maintain any order of elements while TreeSet elements are sorted in ascending order by default.
Similarities:
1) Both HashSet and TreeSet does not hold duplicate elements, which means both of these are duplicate free.
2) If you want a sorted Set then it is better to add elements to HashSet and then convert it into TreeSet rather than creating a TreeSet and adding elements to it.
3) Both of these classes are non-synchronized that means they are not thread-safe and should be synchronized explicitly when there is a need of thread-safe operations.
Examples:
HashSet example
import java.util.HashSet;
class HashSetDemo{
public static void main(String[] args) {
// Create a HashSet
HashSet<String> hset = new HashSet<String>();
//add elements to HashSet
hset.add("Abhijeet");
hset.add("Ram");
hset.add("Kevin");
hset.add("Singh");
hset.add("Rick");
// Duplicate removed
hset.add("Ram");
// Displaying HashSet elements
System.out.println("HashSet contains: ");
for(String temp : hset){
System.out.println(temp);
}
}
}
Output:
HashSet contains:
Rick
Singh
Ram
Kevin
Abhijeet
TreeSet example
import java.util.TreeSet;
class TreeSetDemo{
public static void main(String[] args) {
// Create a TreeSet
TreeSet<String> tset = new TreeSet<String>();
//add elements to TreeSet
tset.add("Abhijeet");
tset.add("Ram");
tset.add("Kevin");
tset.add("Singh");
tset.add("Rick");
// Duplicate removed
tset.add("Ram");
// Displaying TreeSet elements
System.out.println("TreeSet contains: ");
for(String temp : tset){
System.out.println(temp);
}
}
}
Output: Elements are sorted in ascending order.
TreeSet contains:
Abhijeet
Kevin
Ram
Rick
Singh