黑马程序员技术交流社区
标题:
Tre存储问题eSet
[打印本页]
作者:
范龙波
时间:
2013-4-30 23:28
标题:
Tre存储问题eSet
本帖最后由 范龙波 于 2013-5-1 18:27 编辑
import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet t=new TreeSet();
t.add(new Student("zhangsan",18));
t.add(new Student("lisi",22));
t.add(new Student("wangmazi",33));
//t.add(new Student("wangmazi01",33));
Iterator i=t.iterator();
while (i.hasNext())
{
Student.sop(i.next());
Student s=(Student)i.next();
System.out.println(s.GetName()+s.GetAge());
}
}
}
class Student implements Comparable
{
private String name;
private int age;
public String GetName()
{
return name;
}
public int GetAge()
{
return age;
}
Student(String name,int age)
{
this.name=name;
this.age=age;
}
public int compareTo(Object obj)
{
if(!(obj instanceof Student))
throw new RuntimeException("不是学生");
Student s=(Student)obj;
if(this.age>s.age)
return 1;
if(this.age==s.age)
return 0;
return -1;
}
public static void sop(Object obj)
{
System.out.println(obj);
}
} //这个代码打印的结果出现了异常,可我没有找到我哪里写错了,能告诉下我哪里的代码写错了吗谢谢。编译没有错误,可是打印却出问题。
作者:
张洪慊
时间:
2013-4-30 23:52
错误提示:Exception in thread "main" java.util.NoSuchElementException //没有这个元素异常->说明遍历出问题了
while (i.hasNext())
{
//Student.sop(i.next());//注释掉
Student s=(Student)i.next();
System.out.println(s.GetName()+s.GetAge());
}
/*
在while循环中两次用了next()导致游标(指针)发生两次变化
例:第一次循环:经过两次next()后,此时指针指向wangmazi
第二次循环:输出wangmazi,再次next->NoSuchElementException.
*/
复制代码
作者:
wudongzhe
时间:
2013-4-30 23:56
修改如下:
import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet<Student> t=new TreeSet<Student>();
t.add(new Student("zhangsan",18));
t.add(new Student("lisi",22));
t.add(new Student("wangmazi",33));
Iterator<Student> i=t.iterator();
while (i.hasNext())
{
// Student.sop(i.next()); //你打印对象干嘛?。。。 这是这个错的
Student s=i.next();
System.out.println(s.GetName()+s.GetAge());
}
}
}
class Student implements Comparable<Student>
{
private String name;
private int age;
public String GetName()
{
return name;
}
public int GetAge()
{
return age;
}
Student(String name,int age)
{
this.name=name;
this.age=age;
}
public int compareTo(Student s)
{
if(this.age>s.age)
return 1;
if(this.age==s.age)
return 0;
return -1;
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
复制代码
作者:
范龙波
时间:
2013-5-1 18:26
吴东泽 发表于 2013-4-30 23:56
修改如下:
谢了,明白了,next方法在while语句中存在了两次容易出现那个错误。受教了。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2