Iterator over HashMap in Java

后端 未结 9 1667
醉酒成梦
醉酒成梦 2021-02-07 05:43

I tried to iterate over hashmap in Java, which should be a fairly easy thing to do. However, the following code gives me some problems:

HashMap hm = new HashMap(         


        
9条回答
  •  醉酒成梦
    2021-02-07 06:34

    Map carMap = new HashMap(16, (float) 0.75);
    

    // there is no iterator for Maps, but there are methods to do this.

            Set keys = carMap.keySet(); // returns a set containing all the keys
            for(String c : keys)
            {
    
                System.out.println(c);
            }
    
            Collection values = carMap.values(); // returns a Collection with all the objects
            for(Car c : values)
            {
                System.out.println(c.getDiscription());
            }
            /*keySet and the values methods serve as “views” into the Map.
              The elements in the set and collection are merely references to the entries in the map, 
              so any changes made to the elements in the set or collection are reflected in the map, and vice versa.*/
    
            //////////////////////////////////////////////////////////
            /*The entrySet method returns a Set of Map.Entry objects. 
              Entry is an inner interface in the Map interface.
              Two of the methods specified by Map.Entry are getKey and getValue.
              The getKey method returns the key and getValue returns the value.*/
    
            Set> cars = carMap.entrySet(); 
            for(Map.Entry e : cars)
            {
                System.out.println("Keys = " + e.getKey());
                System.out.println("Values = " + e.getValue().getDiscription() + "\n");
    
            }
    

提交回复
热议问题