黑马程序员-JavaAPI-16天-6(Map练习)
package string.test; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /* * 每个学生都有对应的归属地 * 学生Student,地址String * 学生属性:姓名,年龄。 * 注意:姓名和年龄相同的视为同一个学生 * 保证学生的唯一性 * * 1.描述学生。 * 2.定义map容器。将学生作为键,地址作为值存入。 * 3.获取map集合中的元素。 */ public class MapDemo4 { public static void main(String[] args) { Map<Student, String> map = new HashMap<Student, String>(); map.put(new Student("zhangsan", 20), "beijing"); map.put(new Student("lisi", 21), "tianjing"); // map.put(new Student("lisi", 21), // "guangzhou");会把上面的的value替换掉(应为存入了相同的Key) map.put(new Student("wangwu", 22), "hunan"); map.put(new Student("zhaoliu", 23), "hubei"); // 第一种取值方式keySet // Set<Student> keySet = map.keySet(); // Iterator<Student> it = keySet.iterator(); // while (it.hasNext()) { // Student key = it.next(); // String value = map.get(key); // System.out.println("姓名:" + key.getName() + ",年龄:" + key.getAge() + // ",地址:" + value); // } // 第二种取值方式keyEntry Set<Map.Entry<Student, String>> keyEntry = map.entrySet(); Iterator<Map.Entry<Student, String>> me = keyEntry.iterator(); while (me.hasNext()) { Map.Entry<Student, String> entry = me.next(); System.out.println("姓名:" + entry.getKey().getName() + ",年龄:" + entry.getKey().getAge() + ",地址:" + entry.getValue()); } } } class Student implements Comparable<Student> { // 学生姓名 private String name; // 学生年龄 private int age; public Student() { } public Student(String name, int age) { 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 ("name:" + this.name + ",age:" + this.age); } // 实现二叉树(treeMap)比较用到的方法 @Override public int compareTo(Student o) { // TODO Auto-generated method stub int num = new Integer(this.age).compareTo(o.age); if (num == 0) { return this.name.compareTo(o.name); } return num; } // 凡是需要用hash集合存储的类都要实现hashCode 和 equals 方法 // 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; } }