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 map = new HashMap();
        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 s = map.keySet();
        for(Iterator it=s.iterator();it.hasNext();){
            System.out.println(map.get(it.next()));
        }

        //用entrySet()方法实现遍历
        /*Set> e=map.entrySet();
        for(Iterator> it=e.iterator();it.hasNext();){
            System.out.println(it.next());
        }*/

        //用values()方法实现遍历
       /*Collection s = map.values();
        for(Iterator 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();
    }
}

转载于:https://www.cnblogs.com/sail_out_to_sea/archive/2010/10/30/1865119.html

你可能感兴趣的:(HashMap的三种遍历方法)