黑马程序员技术交流社区
标题:
遍历
[打印本页]
作者:
qwerty123321
时间:
2016-6-5 22:18
标题:
遍历
(1)定义一个学生类Student,包含属性:姓名(String name)、年龄(int age)
(2)定义Map集合,用Student对象作为key,用字符串(此表示表示学生的住址)作为value
(3)利用四种方式遍历Map集合中的内容,格式:key::value
作者:
yourlike
时间:
2016-6-5 22:33
太长了,不想写
作者:
左言
时间:
2016-6-5 22:55
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 + "]";
}
}
作者:
左言
时间:
2016-6-5 22:58
求赏点黑马币
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2