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)异常
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)异常
ts.add("woshixuesheng");
你这里添加了一个string类型数据,
但是下面迭代输出的时候,又强制类型转换为Student类型,自然不行了
Student st=(Student)it.next();
类型转换错误
++正解,另外如无必要可以不用抛出自定义异常,因为抛出一个自定义异常会很耗费资源。
可以使用System.err.println("输出警示语句");