class Teacher {
private String name;
private int age;
public Teacher() {
super();
}
public Teacher(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;
Teacher other = (Teacher) 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;
}
}
public class HashMapTest {
public static void main(String[] args) {
//创建集合对象
HashMap<Teacher,String> hm = new HashMap<Teacher,String>();
//添加元素
hm.put(new Teacher("小曼老师", 18), "itcast001");
hm.put(new Teacher("范老师", 28), "itcast002" );
hm.put(new Teacher("邹老师", 32), "itcast003");
hm.put(new Teacher("邹老师", 32), "itcast004");
//遍历
// 键找值
Set<Teacher> keys = hm.keySet();
for (Teacher t : keys) {
String value = hm.get(t);
System.out.println(value +"--"+ t.getName() + "--" + t.getAge());
}
// 键值对 元素, 找键找值
// a: 获取所有的键值对对象
Set<Entry<Teacher, String>> entrySet = hm.entrySet();
// b: 获取到每一个键值对元素对象
for (Entry<Teacher, String> entry : entrySet) {
// 通过键值对元素对象, 找键 找值
Teacher t = entry.getKey();
String value = entry.getValue();
System.out.println( value +"--"+ t.getName() + "--" + t.getAge());
}
}
}
|