TreeSet with custom comparable.

 Using comparable to set the order of Objects in TreeSet
 * Here we are creating a class Contact and each object of this class will represent contact of a person.
 * In TreesetDemo1 class, we will create multiple objects of this class with different values of variables.
 * After creating objects, we will add them to TreeSet and test their order.
 * Here we are implementing Com parable interface to the class that will provide object to be placed into ordered way into TreeSet.
* It has only single method compareTo(OtherObject obj) that will return int value.
* The Object that implements Comparable interface properly, is placed into ordered way automatically.

package collection.demos;

import java.util.TreeSet;

class Contact implements Comparable<Contact>{

    String name;

    String email;

    long phone;

    public Contact(String name, String email, long phone) { = name; = email; = phone;


    public String toString() {

        return name+"\t"+email+"\t"+phone;


    public int compareTo(Contact o) {

        int diff=name.compareTo(;

        return diff;



public class TreeSetDemo2 {

    public static void main(String[] args) {

        TreeSet<Contact> contacts=new TreeSet<Contact>();

        Contact c1=new Contact("zyan","",123467);

        Contact c2=new Contact("corb","",534544);

        Contact c3=new Contact("gogle","",33444);

        Contact c4=new Contact("sraf","",255346);





        for (Contact c : contacts) {







corb        534544

gogle        33444

sraf        255346

zyan        123467


1 comment:

Anonymous said...

Thanx for the Code I was Stuck in middle of program.

Popular Posts