日期:2014-05-20 浏览次数:20946 次
import java.util.*; public class TestCollection01 { public static void main(String[] args) { Collection c = new TreeSet<Stu>(); Stu s1 = new Stu("小红", 20); Stu s2 = new Stu("小明", 21); c.add(s1); c.add(s2); for(Iterator<Stu> it = c.iterator();it.hasNext();) { Stu s = it.next(); System.out.println(s.toString()); } } } class Stu { private String name; private int age; public Stu(String name,int age) { this.name = name; this.age = age; } public int hashCode() { return 1; } public String toString() { return "姓名:" + name +"年龄" + age; } }
Exception in thread "main" java.lang.ClassCastException: com.test02.Stu 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 com.test02.TestCollection01.main(TestCollection01.java:8)