OK,帮你改了下,可以了。
- import java.util.Iterator;
- import java.util.TreeSet;
- //import day15.Student;
- class student implements Comparable{
- private int age ;
- private String name;
- public int getAge() {
- return age;
- }
- public String getName() {
- return name;
- }
- student(int age, String name) {
- super();
- this.age = age;
- this.name = name;
- }
- @Override
- 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 int compareTo(Object o) {
- student n = (student)o;
- int num = new Integer(this.age).compareTo(new Integer(n.age));
- if(num==0){
- return this.name.compareTo(n.name);
- }
- return num;
- }
-
- @Override
- 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 [age=" + age + ", name=" + name + "]";
- }
-
-
-
- }
- public class TreeSetDemo1 {
- /**
- * @param args
- */
- public static void main(String[] args) {
- TreeSet ts = new TreeSet();
- ts.add(new student(12,"aaaaaa"));
- //ts.add(new Student("lisi01",22));
- ts.add(new student(112,"aaaaaa"));
- ts.add(new student(122,"aaaaaa"));
- ts.add(new student(132,"aaaaaa"));
- ts.add(new student(12,"bbbbbb"));
-
- System.out.println(ts);
- Iterator it = ts.iterator();
- while(it.hasNext()){
- student stu =(student) it.next();
- System.out.println(stu.getAge()+"::::::"+stu.getName());
- }
- }
- }
复制代码
运行结果是:[student [age=12, name=aaaaaa], student [age=12, name=bbbbbb], student [age=112, name=aaaaaa], student [age=122, name=aaaaaa], student [age=132, name=aaaaaa]]
12::::::aaaaaa
12::::::bbbbbb
112::::::aaaaaa
122::::::aaaaaa
132::::::aaaaaa
|