Map_TreeMap集合

/*

需求:对学生对象的年龄进行升序排序



因为数据是以键值对形式存在的



所以要使用可以排序的Map集合:TreeMap

*/

import java.util.Comparator;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import java.util.Set;

import java.util.TreeMap;



public class TreeMap_Test {

    public static void main(String[] args) {

        TreeMap<Student,String> tm = new TreeMap<Student,String>();

        tm.put(new Student("lishi1",20),"北京");

        tm.put(new Student("lishi8",23),"深圳");

        tm.put(new Student("lishi3",22),"上海");

        tm.put(new Student("lishi5",21),"重庆");





        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 stu = me.getKey();

            String addr = me.getValue();

            System.out.println(stu+":...:"+addr);

        }

    }



}

class Student implements Comparable<Student>{

    private String name;

    private int age;

    

    Student(String name,int age){

        this.name = name;

        this.age = age;

    }



    public int compareTo(Student s){

        int num = new Integer(this.age).compareTo(new Integer(s.age));



        if(num==0)

            return this.name.compareTo(s.name);

        return num;

    }



    public int hashCode(){

        return name.hashCode()+age*34;

    }

    public boolean equals(Object obj){

        if (!(obj instanceof Student))

            //return false;

            throw new ClassCastException("类型不匹配");



        Student s = (Student)obj;



        return this.name.equals(s.name) && this.age == s.age;

    }

    public String getName(){

        return name;

    }

    public int getAge(){

        return age;

    }

    public String toString(){

        return name+"..."+age;

    }

}

//定义一个以姓名排序的工具

class StuNameComparator 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;

    }

}

 

你可能感兴趣的:(TreeMap)