package com.rf.xs.map;
public class Student implements Comparable<Student> {
private String name;
private int 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 Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(Student o) {
// TODO Auto-generated method stub
if (o instanceof Student) {
Student stu = (Student) o;
int num = this.name.compareTo(stu.name);
if (num == 0) {
if (this.age > stu.age)
return 1;
if (this.age == stu.age) {
return 0;
}
return -1;
}
return num;
}
return 0;
}
}
package com.rf.xs.map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class Stu {
public static void main(String[] args) {
Student s1 = new Student("b", 15);
Student s2 = new Student("a", 16);
Student s3 = new Student("c", 16);
HashMap<Student, String> m = new HashMap<Student, String>();
m.put(s1, "成都");
m.put(s3, "上海");
m.put(s2, "北京");
//Set<Student> ts =new TreeSet<Student>(set);
Set<Student> set =m.keySet();
Set<Student> ts =new TreeSet<Student>();
ts.addAll(set);
Iterator<Student> it = ts.iterator();
while(it.hasNext()){
Student stu = it.next();
System.out.println(stu+" "+m.get(stu));
}
}
}