我想得到HashMap的所有key和value,把他们打印出来。
我自己想的一个办法绕来绕去的,麻烦,请问有没有好点的办法

解决方案 »

  1.   

    楼主怎么不看api啊
    keySet可以得到key的一个set,
    values可以得到value的一个collection
    entrySet可以得到key=value的一个set
      

  2.   

    楼上说的没错,通常通过Set在得到Iterator进行遍历
      

  3.   

    void putAllForCreate(Map m) { 
       for (Iterator i = m.entrySet().iterator(); i.hasNext(); ) {
         Map.Entry e = (Map.Entry) i.next(); 
         putForCreate(e.getKey(), e.getValue());
       }
    }
      

  4.   

    void putAllForCreate(Map m) { 
       for (Iterator i = m.entrySet().iterator(); i.hasNext(); ) {
         Map.Entry e = (Map.Entry) i.next(); 
             System.out.println(e.getKey().toString()); 
             System.out.println(e.getValue().toString());
       }
    }
      

  5.   

    package learn;import java.util.Collection;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Set;public class LearnMap1 {    public Map creatMap() {
            Map m = new HashMap();
            for (int i = 0; i < 10; i++) {
                m.put(new Integer(i), new Integer(i));
            }
            return m;
        }    public Set getMapKey(Map m) {
            return m.keySet();
        }    public Collection getMapValues(Map m) {
            return m.values();
        }    public void printKey(Set s) {
            for (Iterator it = s.iterator(); it.hasNext();) {
                int temp = ((Integer) it.next()).intValue();
                System.out.println("key:" + temp);
            }
        }    public void printValue(Collection c) {
            for (Iterator iter = c.iterator(); iter.hasNext();) {
                int values = ((Integer) iter.next()).intValue();
                System.out.println("value:" + values);
            }
        }    public void printAll(Map m) {
            for (Iterator i = m.entrySet().iterator(); i.hasNext();) {
                Map.Entry e = (Map.Entry) i.next();
                System.out.println(e.getKey()+" "+e.getValue());;
            }
        }    public static void main(String[] args) {
            LearnMap1 lm = new LearnMap1();
            Map map = lm.creatMap();
            Set key = lm.getMapKey(map);
            lm.printKey(key);
            Collection values = lm.getMapValues(map);
            lm.printValue(values);
            lm.printAll(map);
        }
    }
      

  6.   

    Collection coll =hashmap.values();
    Iterator it= coll.iterator();
    while(it.hasNext()){
         用it.next();取就OK了
    }
    建议好好熟悉类库!