-1

I want to add employee object in TreeSet and want to print object

public class DemoTest 
{    
    public static void main(String[] args)
    {       
        TreeSet<Employee> list = new TreeSet<Employee>();           
        list.add(new Employee("A",1));
        list.add(new Employee("A1",11));
        list.add(new Employee("A1",11));

        for(Employee e : list)
        {
            System.out.println(e.getName());
            System.out.println(e.getId());
        }
    }    
}

Employee class is there but getting this exception

mKorbel
  • 109,525
  • 20
  • 134
  • 319
user1668782
  • 179
  • 1
  • 11
  • Exception in thread "main" java.lang.ClassCastException: Employee cannot be cast to java.lang.Comparable at java.util.TreeMap.compare(Unknown Source) at java.util.TreeMap.put(Unknown Source) at java.util.TreeSet.add(Unknown Source) at DemoTest.main(DemoTest.java:14) – user1668782 May 19 '14 at 07:18
  • 2
    Does your Employee class implement the Comparable interface? – Alexis C. May 19 '14 at 07:18
  • Ok, apparently it doesn't so either you need to do this, or you can precise a custom comparator when creating your TreeSet. As the doc says _"All elements inserted into a sorted set must implement the Comparable interface (or be accepted by the specified comparator). Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) (or comparator.compare(e1, e2)) must not throw a ClassCastException for any elements e1 and e2 in the sorted set. Attempts to violate this restriction will cause the offending method or constructor invocation to throw a ClassCastException."_ – Alexis C. May 19 '14 at 07:20
  • @ZouZou Employee class is not implementing the Comparable interface, Why does we need to implement Comparable interface? – user1668782 May 19 '14 at 07:22
  • Because this is the mechanism the TreeSet uses to compare its elements and impose and ordering + the uniqueness. Read the javadoc, it's well explained. – Alexis C. May 19 '14 at 07:24
  • @ZouZou - That must be an answer :P – TheLostMind May 19 '14 at 07:25
  • 1
    @WhoAmI It has already been answered (see the duplicated question ;) ) – Alexis C. May 19 '14 at 07:26
  • 1
    @ZouZou - still you gave a 6 line explaination :) – TheLostMind May 19 '14 at 07:29

1 Answers1

0

Employee must be Comparable :

public class Employee implements Comparable<Employee> {

    ....

    @Override
    public int compareTo(Employee o) {
        return Integer.compare(this.getId(), o.getId());
    }
}
Farvardin
  • 5,336
  • 5
  • 33
  • 54