import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeMap;
public class fanxing {
public static void main(String args[]) {
TreeMap<Student, String> tm=new TreeMap<Student, String>(new MyCompl());
tm.put(new Student("a", 19), "shandong");
tm.put(new Student("a", 18), "tianjin");
tm.put(new Student("lisi", 19), "beijing");
tm.put(new Student("wangwu", 24), "chengdu");
tm.put(new Student("zhaoliu", 20), "shenyang");
tm.put(new Student("sunsi", 21), "shandong");
HashMap<Student, String> hm = new HashMap<Student, String>();
hm.put(new Student("hzhangsan", 19), "shandong");
hm.put(new Student("hzhangsan", 19), "tianjin");
hm.put(new Student("hlisi", 19), "beijing");
hm.put(new Student("hwangwu", 24), "chengdu");
hm.put(new Student("hzhaoliu", 20), "shenyang");
hm.put(new Student("hsunsi", 21), "shandong");
Iterator<Student> it = tm.keySet().iterator();
while (it.hasNext()) {
Student stu = it.next();
String name = stu.getName();
int age = stu.getAge();
String addr=tm.get(stu);
System.out.println(name + ":" + age+":"+addr);
}
Iterator<Student> itor = hm.keySet().iterator();
while (itor.hasNext()) {
Student stu = itor.next();
String name = stu.getName();
int age = stu.getAge();
String addr=hm.get(stu);
System.out.println(name + ":" + age+":"+addr);
}
}
}
class MyCompl implements Comparator<Student>{
public int compare(Student o1, Student o2) {
int num= o1.getName().compareTo(o2.getName());
if(num==0){
return o1.getAge()-o2.getAge();
}
return num;
}
}
class Student implements Comparable<Student> {
private String name;
private int age;
Student(String name, int age) {
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 boolean equals(Object obj) {
if (!(obj instanceof Student))
return false;
Student s = (Student) obj;
return this.name.equals(s.name) && this.age == s.age;
}
public int hashCode() {
return name.hashCode() + age * 39;
}
public int compareTo(Student o) {
int num = this.getAge() - o.getAge();
if (num == 0) {
return this.getName().compareTo(o.getName());
}
return num;
}
}
java-按照学生姓名排序
最新推荐文章于 2024-07-22 04:03:36 发布