forked from sPredictorX1708/Ultimate-Java-Resources
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeSetExample.java
More file actions
34 lines (24 loc) · 1.69 KB
/
TreeSetExample.java
File metadata and controls
34 lines (24 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// This is a java program to display the use of the java.util.TreeSet class
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
System.out.println("TreeSet is like HashSet but it sorts the elements in ascending order.");
TreeSet<String> treeSet = new TreeSet<String>(); // Instance using Default Constructor
treeSet.add("Simple"); // adding elements using the .add() method
treeSet.add("TreeSet");
treeSet.add("TreeSet");
System.out.println(treeSet); // output will be a set of strings in the instance.
// TreeSet is implemented from the SortedSet interface and will omit duplicates
TreeSet<Integer> duplicateEntryTreeSet = new TreeSet<Integer>();
duplicateEntryTreeSet.add(300);
duplicateEntryTreeSet.add(102);
duplicateEntryTreeSet.add(102); // Duplicate value will not be stored
System.out.println(duplicateEntryTreeSet); // Output will be [102, 300]
// Objects stored in TreeSet should be homogeneous
// and comparable otherwise the program will throw an exception
TreeSet<StringBuilder> builderSet = new TreeSet<StringBuilder>();
builderSet.add(new StringBuilder("T")); // Will result in java.lang.ClassCastException
builderSet.add(new StringBuilder("M"));
builderSet.add(new StringBuilder("I"));
}
}