黑马程序员技术交流社区
标题:
Java基础学习日记 - TreeMap练习
[打印本页]
作者:
qihuan
时间:
2015-7-11 23:28
标题:
Java基础学习日记 - TreeMap练习
本帖最后由 qihuan 于 2015-7-12 07:38 编辑
package practice;
import java.util.*;
/**
* 需求:
* 1.对学生对象的年龄进行升序排序。
* 2.对学生对象的姓名进行升序排序。
* 使用可以排序的Map集合-TreeMap
* @author Qihuan
*
*/
//姓名比较器
class NameComparator implements Comparator<Student> {
public int compare(Student s1, Student s2){
int num = s1.getName().compareTo(s2.getName());
if(num == 0)
return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
return num;
}
}
public class TreeMapTest {
public static void main(String[] args) {
TreeMap<Student,String> tm = new TreeMap<Student, String>(new NameComparator());
tm.put(new Student("Lily", 17), "tianjin");
tm.put(new Student("Bob", 12), "shanghai");
tm.put(new Student("Tom", 29), "shanghai");
tm.put(new Student("Tang", 23), "guangzhou");
tm.put(new Student("Aby", 34), "hainan");
Set<Map.Entry<Student, String>> entrySet = tm.entrySet();
for(Iterator<Map.Entry<Student, String>> it = entrySet.iterator();it.hasNext();){
Map.Entry<Student, String> me = it.next();
Student s = me.getKey();
String addr = me.getValue();
System.out.println(s.getName()+"\t"+s.getAge()+"\t"+addr);
}
}
}
复制代码
class Student implements Comparable<Student>{
//定义姓名、nianl
private String name;
private int age;
//定义方法,传入姓名年龄
public Student(String name, int age) {
// TODO Auto-generated constructor stub
this.name = name;
this.age = age;
}
//获取姓名年龄
public String getName(){
return name;
}
public int getAge(){
return age;
}
//重写equals方法
public boolean equals(Object obj){
if(!(obj instanceof Student))
throw new ClassCastException("类型不匹配!");
Student s = (Student)obj;
return this.name.equals(s.name) && this.age==s.age;
}
public int hashCode() {
return name.hashCode()+age;
}
@Override
public int compareTo(Student s) {
// TODO Auto-generated method stub
int num = new Integer(this.age).compareTo(new Integer(s.age));
if(num==0)
return this.name.compareTo(s.name);
return num;
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2