public class Student {
private String name;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Student(String name, String sex) {
super();
this.name = name;
this.sex = sex;
}
public Student() {
super();
}
}
public class MapStudent {
public static void main(String[] args) {
HashMap stu=new HashMap();
stu.put("jack", new Student("小明","男"));
stu.put("tom", new Student("小李","女"));
stu.put("lucy", new Student("小紅","女"));
Set s=stu.keySet();
Iterator it=s.iterator();
while(it.hasNext()){
String key=(String)it.next();
String value=(String)stu.get(key);
System.out.println(key+value);
}
}
}
默認情況下直接輸出某個對象就是調用對象的toString方法的,那你給Student添加一個toString方法,如下:
public String toString(){
return name+","+sex
}