TreeSet 为什么在使用subSet()时出现指针错误,程序如下
程序代码:
package LianXi2; import java.util.Iterator; import java.util.TreeSet; public class UpdateStu implements Comparable { String name; long id; private UpdateStu(String name, long id) { super(); this.name = name; this.id = id; } public int compareTo(Object o) { UpdateStu updat = (UpdateStu) o; int result = id > updat.id?1:(id>updat.id?0:-1); return result; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getId() { return id; } public void setId(long id) { this.id = id; } public static void main(String[] args) { UpdateStu stu1 = new UpdateStu("王小明",200); UpdateStu stu2 = new UpdateStu("王2明",500); UpdateStu stu3 = new UpdateStu("王3明",3400); UpdateStu stu4 = new UpdateStu("王4明",120); UpdateStu stu5 = new UpdateStu("王5明",530); TreeSet tree = new TreeSet(); tree.add(stu1); tree.add(stu2); tree.add(stu3); tree.add(stu4); tree.add(stu5); Iterator it = tree.iterator(); while(it.hasNext()){ UpdateStu stu = (UpdateStu) it.next(); System.out.println(stu.getName()+""+stu.getId()); } System.out.println("---------------------------------------"); it = tree.headSet(stu2).iterator(); while(it.hasNext()){ UpdateStu stu = (UpdateStu) it.next(); System.out.println(stu.getName()+""+stu.getId()); } System.out.println("---------------------------------------"); it = tree.subSet(stu2,stu3).iterator(); while(it.hasNext()){ UpdateStu stu = (UpdateStu) it.next(); System.out.println(stu.getName()+""+stu.getId()); } } }
上述代码 it = tree.subSet(stu2,stu3).iterator(); 这最后段代码,
改成 it = tree.subSet(stu2,stu4).iterator();
将出现指针错误。十分疑惑!
为什么,想不通。