/**
* 需求:往TreeSet集合中存储自定义对象学生
* 想按照学生的年龄进行排序
* 排序时 当主要条件相同时 一定判断一下次要条件
*
*
*
*/
import java.util.*;
public class TreesetTest1 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
TreeSet ts = new TreeSet();
ts.add(new student("lisi02",22)); //报错 没有为类型 TreeSet 定义方法 add(student)
ts.add(new student("lisi007",20));
ts.add(new student("lisi09",19));
ts.add(new student("lisi02",40));
ts.add(new student("lisi01",40));
Iterator ts=ts.iterator(); //报错 没有为类型 TreeSet 定义方法 iterator()
while(ts.hasNext())
{
student s=(student)ts.next();
System.out.println(s.getname()+"....."+s.getage());
}
}
}
//描述学生
class student implements Comparable
{
private String name;
private int age;
student(String name,int age)
{
this.name=name;
this.age=age;
}
public String getname()
{
return this.name;
}
public int getage()
{
return this.age;
}
public int compareTo(Object obj)
{
if(!(obj instanceof student))
throw new RuntimeException("不是学生");
student stu=(student)obj;
if(this.age>stu.age)
return 1;
if(this.age==stu.age)
{
return this.name.compareTo(stu.name);
}
return -1;
}
}
------解决思路----------------------
除了Iterator ts=ts.iterator();这里你的变量名重名了,别的没啥问题,add访问没报错,亲测
给点建议:Student的S请大写,不知道你为什么不加泛型,是刚开始学集合框架吗?
TreeSet<student> ts = new TreeSet<student>();
------解决思路----------------------
package net.csdn.question;
/**
* 需求:往TreeSet集合中存储自定义对象学生
* 想按照学生的年龄进行排序
* 排序时 当主要条件相同时 一定判断一下次要条件
*/
import java.util.*;
public class TreeSetTest1 {
public static void main(String[] args) {
TreeSet<Student> ts = new TreeSet<Student>();
ts.add(new Student("lisi02", 22));
ts.add(new Student("lisi007", 20));
ts.add(new Student("lisi09", 19));
ts.add(new Student("lisi02", 40));
ts.add(new Student("lisi01", 40));
Iterator<Student> ts1 = ts.iterator();
while (ts1.hasNext()) {
Student s = (Student) ts1.next();
System.out.println(s.getName() + "....." + s.getAge());
}
}
}
class Student implements Comparable<Student> {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int compareTo(Student student) {
int result = -1;
if (age > student.age) {
result = 1;
} else if (age == student.age) {
result = name.compareTo(student.name);
} else {
result = -1;
}
return result;
}
}
------解决思路----------------------
正解,应该需要使用泛型