• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Why does it give exception

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.util.*;
public class test{
public static void main(String a[]){
Set s = new TreeSet();
s.add(new Person(20));
s.add(new Person(10));
System.out.println(s);
}
}
class Person{
Person(int i){}
}
[ October 04, 2006: Message edited by: rimzy abdulkader ]
 
Ranch Hand
Posts: 572
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
TreeSet requires that objects added to it should implements Comparable.

Check this out i have modified your code here

 
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You did not override the equals() and hashCode() methods.

I think you should override them in order to use TreeSet.

Am I right? or it is not necessary?
 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
equals() and hashCode() methods should be overridden if we want to store
the objects in HashSet or LinkedHashSet or HashMap or LinkedHashMap.

If you want to store the objects in TreeSet or TreeMap you should can override compareTo() method. This will provide the NATURAL ORDERING.

We can also manage by not implementing 'compareTo()' but passing OUR IMPLEMENTATION of 'Comparator' INTERFACE to the TreeSet/TreeMap constructors. Comparator interface provides 'comparable(Object o1, Object o2) method which should be overridden.

We need not override equals() and hashCode() for TreeSet and TreeMap.

Ranchers please correct me.....
 
Politics n. Poly "many" + ticks "blood sucking insects". Tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic