a- /**
- * HashMap<student,String>
- * 当键的成员变量一致时,认为是同一对象
- */
- package fmi1;
- import java.util.HashMap;
- import java.util.Map.Entry;
- import java.util.Set;
- public class HashMapDemo2 {
- public static void main(String[] args) {
- //建立集合
- HashMap<Student,String> hm = new HashMap<Student,String>();
- //添加元素
- hm.put(new Student("Lily",18),"成都");
- hm.put(new Student("Lily",18),"重庆");
- hm.put(new Student("Luly",19),"成都");
- hm.put(new Student("Leida",15),"北京");
- hm.put(new Student("Li",18),"上海");
- //遍历集合
- Set<Student> set = hm.keySet();
- for(Student s:set)
- System.out.println(s.getName()+"..."+s.getAge()+"..."+hm.get(s));
- System.out.println("-------------------------------- ");
- Set<Entry<Student,String>> st = hm.entrySet();//全部键值对
- for(Entry<Student,String> s:st){
- System.out.println(s.getKey().getName()+"..."+s.getKey().getAge()+".."+s.getValue());
- }
- }
- }
- package fmi1;
- public class Student {
- private String name;
- private int age;
- 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;
- }
- @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;
- }
-
- }
复制代码 |
|