What if you want to store user defined objects in TreeSet ?

Consider this example:
import java.util.*;
class Address
{
String name;
Integer age;
String city;
Address(String name,Integer age,String city){
this.name=name;
this.age=age;
this.city=city;
}};
class demo
{
public static void main(String[] args){
Address add1=new Address("bhabani",24,"blore");
Address add2=new Address("sudeep",25,"mumbai");
TreeSet
hs=new TreeSet
();
hs.add(add1);
hs.add(add2);
System.out.println(hs);
}};
If you compli this prog then success but when you try to run the program then you will get Exception like this:
Exception in thread "main" java.lang.ClassCastException: Address cannot be cast
to java.lang.Comparable
at java.util.TreeMap.put(TreeMap.java:542)
at java.util.TreeSet.add(TreeSet.java:238)
at demo.main(demo.java:26)
TreeSet has its own comparator through which it sorts the elements(which are comparable).
The Address class is not comparable(like String,Integer etc).
So we have to make the Address class Comparable.
See the below Example:

import java.util.*;
class Address implements Comparable

{
String name;
Integer age;
String city;
Address(String name,Integer age,String city){
this.name=name;
this.age=age;
this.city=city;
}
public String getname(){return name;}
public String toString(){
return "name="+name+"\tage="+age+"\tcity="+city+"\n";
}
public int compareTo(Address add){
return name.compareTo(add.getname());
}};
class demo
{
public static void main(String[] args){
Address add1=new Address("bhabani",24,"blore");
Address add2=new Address("sudeep",25,"mumbai");
Address add3=new Address("rishi",23,"mumbai");
Address add4=new Address("bbc",24,"chennai");
Address add5=new Address("pinku",20,"bbsr");
TreeSet
hs=new TreeSet
();
hs.add(add1);
hs.add(add2);
hs.add(add3);
hs.add(add4);
hs.add(add5);
System.out.println(hs);
}};
Now the Address is comparable(user defined).
And it will arrange the objects according to their name.

2 comments:

  1. Error: Address is not abstract and does not override abstract method compareTo(java.lang.Object) in java.lang.Comparable

    ReplyDelete
  2. Nice post and must visit very simple example for sort treeset with user defined object

    http://www.javaproficiency.com/2015/11/how-to-sort-treeset-with-user-defined.html

    ReplyDelete