File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Treeset

 
Shanky Sohar
Ranch Hand
Posts: 1051
Eclipse IDE Firefox Browser
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this program is from examlab..........
why this program is throwing classcast exception............
import java.util.TreeSet;

public class Test2{

public static void main(String args[])
{
TreeSet<Test2> at=new TreeSet<Test2>();
at.add(new Test2());
at.add(new Test2());
at.add(new Test2());
System.out.println(at.first());
}
}
 
Henry Wong
author
Marshal
Pie
Posts: 20828
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at the JavaDoc...

http://java.sun.com/javase/6/docs/api/java/util/TreeSet.html

particularly the section on the add() method.


add

public boolean add(E e)

Throws:
ClassCastException - if the specified object cannot be compared with the elements currently in this set


Henry

 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i.e, Test2 must implements either Comparable or Comparator
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
TreeSet class is a sorted collections, so there should be a way to sort the object, which you want to store, so you must implements Comparable{compareTo()} or Comparator{i]Compare()[/i]} and override those methods accordin to your own sorting order.
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Go through the javadoc for TreeSet to understand its behavior.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic