import java.util.HashMap;
import java.util.Set;
public class demo15 {
/**
* 11.題目:编写一个类,在main方法中定义一个Map对象(采用泛型),
* 加入若干个对象,然后遍历并打印出各元素的key和value。
*/
public static void main(String[] args) {
HashMap<Integer, Person> map=new HashMap<Integer,Person>();
Person p1=new Person("liu", 26);
Person p2=new Person("zhao", 26);
map.put(1, p1);
map.put(2, p2);
Set<Integer> keySet = map.keySet();
for (Integer thisiInteger : keySet) {
Person thisPerson=map.get(thisiInteger);
System.out.println(thisPerson);
}
}
}
public class Person {
private String name;
private int age;
Person(String name,int age){
this.name=name;
this.age=age;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int hashCode(){
final int prim=31;
int result=1;
result=prim*result+age;
result=prim*result+((name==null)?0:name.hashCode());
return result;
}
public boolean equals( Object obj){
if(!(obj instanceof Person))
return false;
Person other=(Person)obj;
return (this.name.equals(other.name))&&this.age==other.age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
|
|