Collection<student> coll = new ArrayList<student>();
coll.add(new student("asd1",23));
coll.add(new student("as2d2",24));
coll.add(new student("assd3",22));
coll.add(new student("azsd4",21));
TreeSet<people> ts = new TreeSet<people>(coll);
ts.add(new people("asd5",34));
for (Iterator<people> it = ts.iterator(); it.hasNext();) {
people pe = it.next();
System.out.println(pe.getName());
}
}
}
复制代码
报错原因:
Exception in thread "main" java.lang.ClassCastException: genericTest.student cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(TreeMap.java:1290)
at java.util.TreeMap.put(TreeMap.java:538)
at java.util.TreeSet.add(TreeSet.java:255)
at java.util.AbstractCollection.addAll(AbstractCollection.java:344)
at java.util.TreeSet.addAll(TreeSet.java:312)
at java.util.TreeSet.<init>(TreeSet.java:160)
at GenericDemo5.main(GenericDemo5.java:26)