HashMapDemo
- package com.itheima.Map;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Set;
- import com.itheima.domain.Employe;
- public class HashMapDemo {
- /**
- * @param args
- * 练习:
- * 将员工和户口所在地存储到HashMap"容器"。
- * 要求:
- * 同姓名,同年龄,视为同一个员工。按照年龄从小到大的顺序,对员工进行排序
- *
- * 分析:
- * 1、定义一个员工类,包含姓名,年龄等
- * 2、员工和户口所在地是一种映射关系
- */
- public static void main(String[] args) {
- /*
- * 建立HashMap"容器"。
- */
- Map<Employe,String> map=new HashMap<Employe, String>();
- /*
- * 存储HashMap"容器"元素
- */
- map.put(new Employe("xiaoqiang",18), "beijing");
- map.put(new Employe("wangqiang",28), "tianjin");
- map.put(new Employe("chenqiang",36), "shanghai");
- /*
- * 获取Map“容器”元素
- */
- Set<Employe> keySet=map.keySet();
- for (Employe employe : keySet) {
- String value=map.get(employe);
- System.out.println(employe.getName()+":"+employe.getAge()+"........"+value);
- }
- }
- }
复制代码
Employe
- package com.itheima.domain;
- public class Employe {
- private String name;
- private int age;
-
- public Employe() {
- super();
-
- }
-
- public Employe(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;
- }
- @Override
- public String toString() {
- return "Employe [name=" + name + ", age=" + age + "]";
- }
- @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;
- Employe other = (Employe) 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;
- }
-
-
- }
复制代码
这个怎么就实现了“按照年龄从小到大排序”,我知道这“文章”在hashcode()和equals(),所以能不能帮我解读一下,这个两个方法中的代码是什么意思?
|
|