File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package TreeSet ;
2+
3+ import java .util .TreeSet ;
4+ import java .util .Iterator ;
5+ import java .util .Comparator ;
6+
7+ class NewTreeComparator implements Comparator <Float > {
8+
9+ public int compare (Float obj1 , Float obj2 ) {
10+
11+ if (((Float )obj1 ).equals ((Float )obj2 )) {
12+ return -1 ;
13+ }
14+
15+ // using compareTo() to ensure
16+ return obj2 .compareTo (obj2 );
17+ }
18+
19+
20+
21+
22+ }
23+
24+ // Main class
25+ // TreeSetDemo class
26+ public class TreeSetDemo17 {
27+ public static void main (String [] args ) {
28+
29+ TreeSet <Float > ts = new TreeSet <>(new NewTreeComparator ());
30+
31+ TreeSet <Float > ts1 = new TreeSet <>(new NewTreeComparator ());
32+
33+ ts .add (10.58f );
34+ ts .add (20.78f );
35+ ts .add (30.65f );
36+ ts .add (10.47f );
37+ ts .add (50.98f );
38+ ts .add (60.65f );
39+
40+ ts1 .add (10.55f );
41+ ts1 .add (20.78f );
42+ ts1 .add (34.65f );
43+ ts1 .add (45.78f );
44+ ts1 .add (57.98f );
45+ ts1 .add (99.65f );
46+
47+
48+ Iterator <Float > it = ts .iterator ();
49+ while (it .hasNext ()) {
50+ System .out .println (it .next ());
51+ }
52+ //As 20.78f is present in both the treeset, it will return -1 . i.e.
53+ //it will end the iterations.
54+
55+ System .out .println (ts .comparator ().compare ( 99.65f , 10.58f )) ;
56+
57+ // Return 0 as both numbers are compared.
58+
59+ System .out .println (ts .comparator ().compare (20.78f , 20.78f )) ;
60+ //Return -1 as both numbers are equal.
61+ }
62+ }
You can’t perform that action at this time.
0 commit comments