看下,能不能解决问题
================================================================
public class Test {
public static void main(String[] args) {
TreeSet ts = new TreeSet(new MyCompare());
ts.add(new Student("lisi02", 22));
ts.add(new Student("lisi007", 20));
ts.add(new Student("lisi09", 19));
ts.add(new Student("lisi06", 18));
ts.add(new Student("lisi007", 29));
Iterator it = ts.iterator();
while (it.hasNext()) {
Student stu = (Student) it.next();
System.out.println(stu.getName() + "...." + stu.getAge());
}
System.out.println("====================使用了泛型====================");
//声明父类创建子类,用下泛型
Set<Student> set = new TreeSet<Student>();
set.add(new Student("lisi02", 22));
set.add(new Student("lisi007", 20));
set.add(new Student("lisi09", 19));
set.add(new Student("lisi06", 18));
set.add(new Student("lisi007", 29));
//因为上面用了泛型所以
Iterator<Student> is = set.iterator();
while (is.hasNext()) {
Student student = is.next();//这里就不用类型强制转换了
System.out.println(student.getName()+"--->"+student.getAge());
}
System.out.println("====================我一般是这样用的====================");
Set<Student> myset = new TreeSet<Student>();//当然使用了泛型之后,你添加其他对象就会报错的如myset.add(new Object());
myset.add(new Student("lisi02", 22));
myset.add(new Student("lisi007", 20));
myset.add(new Student("lisi09", 19));
myset.add(new Student("lisi06", 18));
myset.add(new Student("lisi007", 29));
for (Student student : myset) {
System.out.println(student.getName()+"--->"+student.getAge());
}
}
}
/**
* @title 关于Student类写法的一些建议
* @author Administrator
*
*/
class Student implements Comparable {
private String name;
private int age;
//1.一般类都是有默认构造方法的,就是不带参数的构造方法。类操作多了,你就知道好处了
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 this.name.compareTo(s.name);
}
return -1;
}
//2.get set方法一般也都是成对出现的,编辑器自动生成方式:alt+shift+s -> generate Getters and Setters ->选择变量点击【ok】
//构造方法也可以自动生成
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
class MyCompare implements Comparator {
public int compare(Object o1, Object o2) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
int num = s1.getName().compareTo(s2.getName());
if (num == 0) {
return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
}
return num;
}
}
================================================================= |