- package fuxi1;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Set;
- /**
- * 题目:每一个学生都有对应的归属地,学生Student,归属地String,学生有属性姓名和年龄,属性相同视为同一个学生。保证学生的唯一性。
- * 思路:1.先描述学生,因为要确保唯一性,所以要用HashMap集合,学生类中要覆盖hashCode()和equals()方法。
- * 2.定义Map集合,将学生和归属地作为键值存入
- * 3.获取集合中的元素
- *@author XiaLei
- */
- public class Day16Test4 {
- public static void main(String[] args) {
- Students st1 = new Students("java01",5);
- Students st2 = new Students("java02",2);
- Students st3 = new Students("java04",4);
- Students st4 = new Students("java01",5);
- String addr1 = st1.diZhi("BeiJin01");
- String addr2 = st1.diZhi("BeiJin02");
- String addr3 = st1.diZhi("BeiJin03");
- String addr4 = st1.diZhi("BeiJin04");
-
- Map<Students,String> m = new HashMap<Students,String>();
- m.put(st1,addr1);
- m.put(st2,addr2);
- m.put(st3,addr3);
- m.put(st4,addr4);
- //entrySet取出方式:
- Set<Map.Entry<Students,String>> s = m.entrySet();
- Iterator<Map.Entry<Students,String>> it = s.iterator();
- while(it.hasNext()){
- Map.Entry<Students, String> me = it.next();
- Students key = me.getKey();
- String value = me.getValue();
- System.out.println(key+"="+value);
- }
- //keySet取出方式:
- Set<Students> st = m.keySet();
- for(Iterator<Students> its =st.iterator();its.hasNext();){
- Students key1 = its.next();
- String value1 = m.get(key1);
- System.out.println(key1+"="+value1);
- }
- }
- }
- class Students implements Comparable<Students>{//实现Comparable接口,让Students类具有自然顺序。
- private String name;
- private int age;
- public Students(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- public String diZhi(String addr){
- return addr;
- }
- public String getName() {
- return name;
- }
- public int getAge() {
- return age;
- }
- public int compareTo(Students s){
- int num = this.age-s.age;
- if(num==0){
- return this.name.compareTo(s.name);
- }
- return num;
- }
- public int hashCode(){
- return name.hashCode()+age*39;
- }
- public boolean equals(Object obj){
- if (!(obj instanceof Students))
- throw new RuntimeException("类型不匹配");//注意异常的使用,这里如果return false;没有意义 所以要抛出一个运行时异常。
- Students st = (Students)obj;
- return this.name.equals(st.name) && this.age==st.age;
- }
- public String toString(){
- return "name:"+name+"...age:"+age;
- }
- }
复制代码 |
|