黑马程序员技术交流社区

标题: HashMap 排序 [打印本页]

作者: javaeea    时间: 2015-9-21 22:49
标题: HashMap 排序
package com.heima.bean;

import java.util.Comparator;

public class Student implements Comparable<Student>
{

       
        private String name;
        private int age;
       
        public Student() {
                super();
                // TODO Auto-generated constructor stub
        }
        public Student(String name, int age) {
                super();
                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;
        }
       
        //重写hashCode()和equals(),集合添加元素时调用,元素键重复,值覆盖.
        @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;
        }
       
        @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;
        }
       
        //打印输出格式.
        @Override
        public String toString() {
                return "Student [name=" + name + ", age=" + age + "]";
        }
       
        //重写方法,元素添加时调用,排序.
        @Override
        public int compareTo(Student o) {
                // TODO Auto-generated method stub
                int num = this.age - o.age;
                return num==0?this.name.compareTo(o.name):num;
        }
       
       
        //排序时优先调用
        class MyComparator implements Comparator<Student>{//Comparator<Student>

                @Override
                public int compare(Student o1, Student o2) {
                        int num = o1.age - o2.age;
                        return num==0?o1.name.compareTo(o2.name):num;
                }
               
        }
       
       
}

作者: maxwell247    时间: 2015-9-21 22:56
写得好,向你学习!




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2