import java.util.*;
class TreeSetDemo 
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args) 
{
TreeSet ts = new TreeSet();
ts.add(new Student("Betty002",23));
ts.add(new Student("Betty001",25));
ts.add(new Student("Betty004",34));
ts.add("woshixuesheng");
Iterator it = ts.iterator();
while (it.hasNext())
{
Student st=(Student)it.next();
sop(st.getName()+"-----"+st.getAge());
} System.out.println("Hello World!");
}
}
class Student implements Comparable
{
private String name;
private int age;
Student(String name, int age)
{ this.name =name;
this.age = age; }
 int getAge(){
return this.age;
}
String getName()
{
return this.name;
}
public int compareTo(Object obj)
{
if (!(obj instanceof Student))
try
{
throw (new NotStudentException("不是学生不能参与比较"));
}
catch (NotStudentException e)
{
System.out.println("bushixuesheng");
}

Student st = (Student) obj;
return this.name.compareTo(st.name);
}
}
class NotStudentException extends Exception
{
NotStudentException(String message)
{
  super(message);
}
}
结果
Exception in thread "main" java.lang.ClassCastException: Student cannot be cast
to java.lang.String

        at java.lang.String.compareTo(String.java:108)
        at java.util.TreeMap.put(TreeMap.java:560)
        at java.util.TreeSet.add(TreeSet.java:255)
        at TreeSetDemo.main(TreeSetDemo.java:14)异常