import java.util.*;
public class UpdateStu implements Comparable {
String name;
long id;
public UpdateStu(String name, long id) {
this.id = id;
this.name = name;
}
public int compareTo(Object o) {
UpdateStu upstu = (UpdateStu) o;
int result = id > upstu.id ? 1 : (id == upstu.id ? 0 : -1);
return result;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
UpdateStu stu1 = new UpdateStu("李同学", 01011);
UpdateStu stu2 = new UpdateStu("陈同学", 01021);
UpdateStu stu3 = new UpdateStu("王同学", 01051);
UpdateStu stu4 = new UpdateStu("马同学", 01012);
TreeSet tree = new TreeSet();
tree.add(stu1);
tree.add(stu2);//这里就有问题了
tree.add(stu3);
tree.add(stu4);
Iterator it = tree.iterator();
System.out.println("Set集合中的所有元素:");
while (it.hasNext()) {
UpdateStu stu = (UpdateStu) it.next();
System.out.println(stu.getId() + " " + stu.getName());
}
it = tree.headSet(stu2).iterator();
System.out.println("截取前面部分的集合:");
while (it.hasNext()) {
UpdateStu stu = (UpdateStu) it.next();
System.out.println(stu.getId() + " " + stu.getName());
}
it = tree.subSet(stu2, stu3).iterator();
System.out.println("截取中间部分的集合");
while (it.hasNext()) {
UpdateStu stu = (UpdateStu) it.next();
System.out.println(stu.getId() + " " + stu.getName());
}
}
}
我把上述代码implements Comparable 去掉,运行的时候会有错误,为什么
我检查到了是tree.add(stu1);
tree.add(stu2);//这里就有问题了
tree.add(stu3);
tree.add(stu4);
这里有问题的,那位能给我解释一下啊。。。。。。
------解决方案--------------------
TreeSet是用TreeMap来实现的,他是按照一定顺序存放的,这个排序的依据就是所存放元素的compareTo方法,放第一个的时候无需跟任何元素比较,所以不报错,但是从第二个开始就要比较以决定放置的位置了,这时候就要调用compareTo方法,怎么调用compareTo方法呢,只有将类强制转换为Comparable类型之后才能调用啊,但是若你没有实现Comparable接口,那当然就不能强制准换了,所以就报java.lang.ClassCastException
------解决方案--------------------
首先,让我们来看看JDK中TreeSet类的add方法
- Java code
/** * Adds the specified element to this set if it is not already present. * More formally, adds the specified element {@code e} to this set if * the set contains no element {@code e2} such that * <tt>(e==null ? e2==null : e.equals(e2))</tt>. * If this set already contains the element, the call leaves the set * unchanged and returns {@code false}. * * @param e element to be added to this set * @return {@code true} if this set did not already contain the specified * element * @throws ClassCastException if the specified object cannot be compared * with the elements currently in this set * @throws NullPointerException if the specified element is null * and this set uses natural ordering, or its comparator * does not permit null elements */ public boolean add(E e) { return m.put(e, PRESENT)==null; }
------解决方案--------------------