HashMap的三种遍历方法
一下代码分别:
1、用keyset()和get()方法实现遍历
2、用entrySet()方法实现遍历
3、用values()方法实现遍历
import com.sun.jndi.ldap.Connection;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Administrator
*/
public class StuMapTest {
public static void main(String[] args){
Map<String,Student> map = new HashMap<String, Student>();
Student s1 = new Student("宋江", "1001", 33);
Student s2 = new Student("李逵", "1003", 36);
Student s3 = new Student("公孙胜", "1004", 39);
Student c = map.put("1001", s1);
System.out.println(c);
map.put("1004", s3);
map.put("1003", s2);
//用keyset()和get()方法实现遍历
Set<String> s = map.keySet();
for(Iterator<String> it=s.iterator();it.hasNext();){
System.out.println(map.get(it.next()));
}
//用entrySet()方法实现遍历
/*Set<Map.Entry<String,Student>> e=map.entrySet();
for(Iterator<Entry<String, Student>> it=e.iterator();it.hasNext();){
System.out.println(it.next());
}*/
//用values()方法实现遍历
/*Collection<Student> s = map.values();
for(Iterator<Student> it =s.iterator();it.hasNext();){
System.out.println(it.next());
}*/
}
}
class Student{
String name;
String id;
int age;
public Student(String name, String id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
public String toString(){
return new StringBuilder().append("id:")
.append(this.id).append("name:").append(this.name)
.append("age:").append(this.age).toString();
}
}
posted on 2010-10-30 15:59 sail out to sea 阅读(394) 评论(0) 编辑 收藏 举报