public static void main(String[] args) {
Map<Student, String> tempMap = new HashMap<>();
tempMap.put(new Student("张三",23),"武汉汉口");
tempMap.put(new Student("李四",24),"武汉武昌");
tempMap.put(new Student("王五",25),"武汉汉阳");
System.out.println("方法一");
Iterator it = tempMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
Object key = entry.getKey();
Object value = entry.getValue();
System.out.println(key + "::" + value);
}
System.out.println("");
System.out.println("方法二");
for (Map.Entry<Student, String> entry : tempMap.entrySet()) {
String key = entry.getKey().toString();
String value = entry.getValue().toString();
System.out.println(key + "::" + value);
}
System.out.println("");
System.out.println("方法三");
for (Iterator i = tempMap.keySet().iterator(); i.hasNext();) {
Object obj = i.next();
System.out.println( obj + "::" + tempMap.get(obj));
}
System.out.println("");
System.out.println("方法四");
for (Object o : tempMap.keySet()) {
System.out.println(o + "::" + tempMap.get(o));
}
}
}
class Student{
private String name;
private int age;
public Student() {
super();
// TODO Auto-generated constructor stub
}
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 String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
|