package cn.itcast.compare;
//标准学生类
public class Student implements Comparable<Student> {
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
public int compareTo(Student s) {
int num = this.getAge() - s.getAge();
return num;
}
}
package cn.itcast.compare;
import java.util.Iterator;
import java.util.TreeSet;
import cn.itcast.mapergodic.Student;
//测试类
public class TreeSetDemo {
public static void main(String[] args) {
/**
* 定义一个TreeSet对象,存储自定义对象Student。 按照姓名长度的大小决定存储的顺序,
* 从长到短排序,如果长度一样,年龄小的在前面
*/
//定义一个集合对象,储存元素
TreeSet<Student> ts = new TreeSet<Student>();
//定义元素
Student students1 = new Student("zhangsan",34);
Student students2 = new Student("wangwu",23);
Student students3 = new Student("zhaoliu",33);
Student students4 = new Student("niubi",22);
//添加元素
ts.add(students1);
ts.add(students2);
ts.add(students3);
ts.add(students4);
//遍历
Iterator<Student> it = ts.iterator();
while (it.hasNext()) {
Student students = it.next();
System.out.println(students);
}
}
}
}
|
|