You are on page 1of 10

TreeSet(C) :- It is implementation class of SortedSet(I).

-----------
1)Underlying data structure is balanced Tree.
2)Duplicates are not allowed
3)Insertion order is not preserved.
4)All elements are inserted in some sorting order.
5)In total Collection framework there are 2 areas where heterogenous objects are
not allowed.They are TreeSet and TreeMap. If we try to insert heterogenous obje
cts the you will get Runtime exception called ClassCastException.
6)Null acceptance is allowed but only once it is allowed.If you try to insert m
ore than one null then you will get NullPointerException
TreeSet Constructors :- There are total 4 constructors in TreeSet.First 2 constr
uctors are most commonly used....
---------------------
1)TreeSet tr = new TreeSet(); ---> It creates empty TreeSet object and follows
default natural sorting order. Default natural sorting order means if the elemen
ts are integers then it is ascending order,if the elements are Strings then it f
ollows alphabetical order.
2)TreeSet tr = new TreeSet(Comparator comp); -->If we dont want default natural
sorting order,if we want sorting based on name or id of an Employee object then
we have to define our own comparator.
3)TreeSet tr = new TreeSet(Collection collection); -->It creates equivalent Tree
Set object.
4)TreeSet tr = new TreeSet(SortedSet ss); -->It creates equivalent TreeSet objec
t.
Example :-
--------
class Demo {

public static void main(String args[]) {

Treeset tr = new Treeset(); //creates empty treeset by following default natura
l sorting order.
tr.add("A");
tr.add("a");
tr.add("B");
tr.add("Z");
tr.add("L");
// tr.add(new Integer(10)); //you will get ClassCastException
//tr.add(null); //you will get NullPointerException.
System.out.println(tr); // [A,B,L,Z,a]

}
}
Because the ASCII value of "a" is 97 and "A" is 65. The above program gives the
output in ascending order.

Note :- For the TreeSet heterogenous objects are not allowed if we try to inser
t heterogenous objects then you will get ClassCastException.And if you try to in
sert Null into TreeSet then you will get NullPointerException.
-----
Null Acceptance :-
----------------
1)For non empty TreeSet if we are trying to insert null then you will get NullPo
interException.
2)For Empty TreeSet null is allowed as first element.
After inserting null if we try to insert any other element then we will get Null
PointerException.
Example 2 :-
---------
class Demo {

public static void main(String args[]) {

Treeset tr = new Treeset(); //creates empty treeset by following default natura
l sorting order.
tr.add(new StringBuffer("A"));
tr.add(new StringBuffer("B"));
tr.add(new StringBuffer("Z"));
tr.add(new StringBuffer("L"));
System.out.println(tr);

}
}
compile : - javac Demo.java
Run :- java Demo
then you will get ClassCastException.
-->Even if we are adding homogenous objects y we are getting ClassCastException.
If you are depending on default natural sorting order compulsory the objects sho
uld be homogenous and comparable.
if the objects are not homogenous or if the objects are not comparable then you
will get ClassCastException.
In the above example 1st conditon is satisfied because all objects in above are
homeogenous but StringBuffer class objects are not Comparable because it doesnt
implement Comparable Interface.
Note :- If we are following default natural sorting order then the objects shoul
d be homogenous and Comparable otherwise you will get ClassCastException.
-----
-->An Object is said to be Comparable if and only if the corresponding class mus
t implement Comparable interface.
Comparable(I) :-
--------------
1)Meant for default natural sorting order.
2)It is available in java.lang package.
3)It has only one method.
public int compareTo(Object obj2);

- this returns -ve value iff and only if obj1 has to come before obj2
- this returns +ve value iff and only if obj1 has to come after obj2
- this returns 0 value iff and only if obj1 and obj2 are equal.
whenever we are trying to insert elements into Treeset which is following defaul
t natural sorting order then the JVM will internally call compareTo() method of
Comparable interface every time of insertion.
Example :-
class Demo {
public static void main(String args[]) {
Treeset tr = new Treeset(); //creates empty treeset by following default natural
sorting order.
tr.add("A");
tr.add("X"); "X".compareTo("A") ---> +ve [A,X]
tr.add("L"); "L".compareTo("A") ---> +ve , "L".compareTo("X") ---> -ve [A,L,
X]
tr.add("Z"); "Z".compareTo("A") ----> +ve , "Z".compareTo("X") ----> +ve , "Z".
compareTo("L") ---> +ve [A,L,X,Z]
System.out.println(tr); // [A,L,X,Z]
}
}
Result :-
------
compile :- javac Demo.java
Run :- java Demo
output :- [A,L,X,Z]
Comaparator(I) : -
-----------------
To define our own sorting order.(customized sorting order).
Comparator interface :-
---------------------
1)Used to define customized sorting order.
2)Present in java.util package.
3)It has 2 methods
a) public int compare(Object obj1,Object obj2)
b) public boolean equals(Object obj)

-->Comparable is used for default natural sorting order and Comparator is used f
or customized sorting order.
-->if you are not satisfied with the default natural sorting order and the defau
lt natural sorting order is not provided for the class then we should go for Com
parator interface.
-->If you are trying to insert elements into Treeset and following the default n
atural sorting order the objects must be comparable and Homogenous.
public int compare(Object obj1, Object obj2);

- this returns -ve value iff and only if obj1 has to come before obj2
- this returns +ve value iff and only if obj1 has to come after obj2
- this returns 0 value iff and only if obj1 and obj2 are equal.

--> As the comparator interface contains 2 methods so we have to provide impleme
ntation for 2 methods in our comparator class(according to interface rule).But i
t is optional to implement equals() method implementation.We may think that we a
re violating the interface rule but it is not.For example
Example :-
-------
class MyComparator implements Comparator {

public int compare(Object obj1,Object obj2) {

}

}

-->we know that every class is the sub class of Object class.As the equals() me
thod is defined inside the Object class so it is optional to implement in our Co
mparator class as it is already defined in Object class which is available throu
gh inheritence.


Requirement :- To insert Integer objects into Treeset and it should follow des
cending order.

-->If we are trying to create empty Treeset object it will follow default natur
al sorting order.

-->Default natural sorting order for integer objects is ascending order.

Ex :-

class Demo {

public static void main(String args[]) {

Treeset tr = new Treeset(); //creates empty treeset by following default natura
l sorting order.
tr.add(10);
tr.add(20);
tr.add(5);
tr.add(3);
System.out.println(tr); // [3,5,10,20]

}
}

-->The above program follows default natural sorting order so it is giving the
output in ascending order.If we want to store the elements into treeset as desce
nding order then we have to create our own comparator class and provide it to th
e Treeset Object while creating.


Example1 :-

class MyComparator implements Comparator {

public int compare(Object obj1, Object obj2) {

Integer i1 = (Integer)obj1;
Integer i2 = (Integer)obj2;
if(i1>i2) {
return -1;
} else if(i1<i2) {
return -1;
} else {
return 0;
}
}
}


class Demo [
public static void main(String[] args) {
TreeSet tr = new TreeSet(new MyComparator());
tr.add(20);
tr.add(15); ---> compare(15,20) //whenever we are adding the element(ie after
first element) into Treeset then JVM will check whether the programmer supplied
any comparator or not,if yes then the jvm will call comparator compare() otherwi
se the jvm will call the compareTo() method of Comparable interface.
tr.add(30);
tr.add(8);
tr.add(35);
tr.add(4);
System.out.println(tr); // [35,30,20,15,8,4]
}
}

-->The above program is used for inserting the elements into treeset in descend
ing order.

Example2 :-
--------

class MyComparator implements Comparator {

public int compare(Object obj1, Object obj2) {

Integer i1 = (Integer)obj1;
Integer i2 = (Integer)obj2;
//return i1.compareTo(i2); // Ascending order of elements will be printed [4,8
,15,20,30,35]
// retrun -i1.compareTo(i2); or return i2.compareTo(i1); //Descending orde
r of elements will be printed [35,30,20,15,8,4]

//return +1 ; //insertion order of elements will be printed [20,15,30,8,35,4]
// return -1; // Reverse of insertion order will be printed. [4,35,8,30,15,20
]

return 0; // only first element will be inserted all the other elements are tre
ated as duplicates. [20]
}
}


class Demo [
public static void main(String[] args) {
TreeSet tr = new TreeSet(new MyComparator());
tr.add(20);
tr.add(15); ---> compare(15,20) //whenever we are adding the element(ie after
first element) into Treeset then JVM will check whether the programmer supplied
any comparator or not,if yes then the jvm will call comparator compare() otherw
ise the jvm will call the compareTo() method of Comparable interface.
tr.add(30);
tr.add(8);
tr.add(35);
tr.add(4);
System.out.println(tr); // [35,30,20,15,8,4]
}
}

Requirement :- Insert the Strings in Descending order into Treeset.

Example1 :-
------------

class Demo [
public static void main(String[] args) {
TreeSet tr = new TreeSet(new MyComparator());
tr.add("rama");
tr.add("raju");
tr.add("reena");
tr.add("ravi");
tr.add("shilpa");
tr.add("sharadha");
tr.add("divya");
tr.add("shylaja");
System.out.println(tr); // [shylaja,shilpa,sharadha,reena,ravi,rama,raju,divy
a]
}
}

class MyComparator implements Comparator {

public int compare(Object obj1, Object obj2) {
String s1 = (String)obj1;
String s2 = obj2.toString();
if(s1>s2) {
return -1;
} else if(s1<s2) {
return -1;
} else {
return 0;
}
}
}

-->If you are not passing the comparator object to the Treeset default natural
sorting order will be applied and the output will be [divya,raju,rama,ravi,reen
a,sharadha,shilpa,shylaja]
-->If you are passing the above comparator object to the Treeset then the cust
omized sorting order will be applied and the output will be [shylaja,shilpa,sha
radha,reena,ravi,rama,raju,divya]
Example2 :-
------------

class Demo [
public static void main(String[] args) {
TreeSet tr = new TreeSet(new MyComparator());
tr.add("rama");
tr.add("raju");
tr.add("reena");
tr.add("ravi");
tr.add("shilpa");
tr.add("sharadha");
tr.add("divya");
tr.add("shylaja");
System.out.println(tr); // [shylaja,shilpa,sharadha,reena,ravi,rama,raju,divy
a]
}
}

class MyComparator implements Comparator {

public int compare(Object obj1, Object obj2) {
String s1 = (String)obj1;
String s2 = obj2.toString();

//return s1.compareTo(s2); // [divya,raju,rama,ravi,reena,sharadha,shilpa,shy
laja]
// return -s1.compareTo(s2);// [shylaja,shilpa,sharadha,reena,ravi,rama,raju,
divya]
return s2.compareT0(s1); //[shylaja,shilpa,sharadha,reena,ravi,rama,raju,div
ya]
}

-->If you are not passing the comparator object to the Treeset default natural
sorting order will be applied and the output will be [divya,raju,rama,ravi,reen
a,sharadha,shilpa,shylaja]
-->If you are passing the above comparator object to the Treeset then the cust
omized sorting order will be applied and the output will be [shylaja,shilpa,sha
radha,reena,ravi,rama,raju,divya]


Requirement :- Inserting the StringBuffer Objects into Treeset in alphabetical
order(ie default natural sorting order)
-------------
Example :-
-------

class Demo [
public static void main(String[] args) {
TreeSet tr = new TreeSet(new MyComparator());
tr.add(new StringBuffer("A"));
tr.add(new StringBuffer("Z"));
tr.add(new StringBuffer("K"));
tr.add(new StringBuffer("L"));
System.out.println(tr); // [A,K,L,Z]
}
}

class MyComparator implements Comparator {

public int compare(Object obj1, Object obj2) {
String s1 = obj1.toString();
String s2 = obj2.toString();
return s1.compareTo(s2);

}

Note:- if you are not passing the Comparator object in the above Treeset objec
t then default natural sorting order but StringBuffer object does not have defau
lt natural sorting order(ie objects should be comparable and homogenous) so comp
arator is mandatory to Treeset if you add StringBuffer objects.
-----
if you dont pass comparator object to Treeset object for adding stringbuffer o
bjects then you will get ClassCastException.Because StringBufffer class doesnt i
mplements Comparable interface.



Requirement :- Adding the elements into Treeset by following conditions....
-------------
1)increasing length order.
2)same length (alphabetical order)


class Demo [
public static void main(String[] args) {
TreeSet tr = new TreeSet(new MyComparator());
tr.add("A");
tr.add(new StringBuffer("ABC"));
tr.add(new StringBuffer("AA"));
tr.add("XX");
tr.add("ABCD");
tr.add("A");
System.out.println(tr); // [A,AA,XX,ABC,ABCD]
}
}

class MyComparator implements Comparator {

public int compare(Object obj1, Object obj2) {
String s1 = obj1.toString();
String s2 = obj2.toString();
int l1 = s1.length();
int l2 = s2.length();
if(l1<l2) {
return -1;
} else if (l1>l2) {
return +1;
} else {
return s1.compareTo(s2);
}

}

Note:- If we are depending on default natural sorting order then the objects s
hould be homogenous and comparable otherwise we will get runtime exception calle
d ClssCastException.
-----
But if we are defining our own comparator the objects may not be homogenous or
comparable,we cal also insert heterogenous and non comparable objects also.



Comparable vs Comparator :-
---------------------------

-->For pre defined comparable classes like String, default natural sorting ord
er is already available.if we are not satisfied with the default ordering then w
e can go for our own Comparator.

-->For pre defined non comparable classes like StringBuffer, default natural s
orting order is not available.If we want the default natural sorting order then
we have to define our own comparator object.

-->For user defined class like Employee class
ie the person who is writing the class or developing the class has to provide
default natural sorting order.
and the user of the class can use that class if he is satisfied with it or he
can go with his own Comparator object.

-->For our own classes like Employee,Person,Student, the person who is writing
our own class,he is responsible to define default natural sorting order by impl
ementing Comparable interface.
The person who is using our class, and if he is not satisfied with the
default natural sorting order then he can define his own sorting by implementing
Comparator interface.



Requirement :- User defined objects in some sorting order.
-----------

Example:-
--------
class Employee implements Comparable {

private int empId;
private String empName;
Employee(String empName,int empId) {
this.empId = empId;
this.empName = empName;
}

public String toString() {
return empName + " --->"+ empId;
}

public int compareTo(Object obj) {

int eid1 = this.empId;
Employee e = (Employee)obj;
int eid2 = e.getId();
if(eid1<eid2) {

return -1;
} else(eid1> eid2) {
return +1;
} else {
return 0;
}
}


class ComparableComparatorDemo {

public static void main(String args[]) {
TreeSet t = new TreeSet();
Employee e1= new Employee("naga",100);
Employee e2= new Employee("balakrishna",200);
Employee e3= new Employee("chiranjeevi",50);
Employee e4= new Employee("venkatesh",150);
Employee e5= new Employee("naga",100);

t.add(e1);
t.add(e2);
t.add(e3);
t.add(e4);
t.add(e5);
System.out.println(t); //default natural sorting order. [chiranjeevi-->50,naga-
->100,venkatesh-->150,balakrishna-->200]

TreeSet t = new TreeSet(new MyComparator());
Employee e1= new Employee("naga",100);
Employee e2= new Employee("balakrishna",200);
Employee e3= new Employee("chiranjeevi",50);
Employee e4= new Employee("venkatesh",150);
Employee e5= new Employee("naga",100);

t.add(e1);
t.add(e2);
t.add(e3);
t.add(e4);
t.add(e5);
System.out.println(t); //customized sorting order based on name. [balakrishna-
->200,chiranjeevi-->50,naga-->100,venkatesh-->150]
}

}


class MyComparator implements Comparator {

public int compare(Object obj1, Object obj2) {
Employee emp1 = (Employee)obj1;
Employee emp2 = (Employee)obj2;
String empName1 = obj1.getEmpName();
String empName2 = obj2.getEmpName();
emp1.compareTo(emp2);

}
}

------------------------------------------------------------------------------
-------------------------------------------------------------------

You might also like