简体   繁体   中英

Java: problem with hashmap and keyset()

Here's what I'm doing (it's my "homework"): the assignment is to make a map of gerbils and then flip through it using keySet() and get(key);

import java.util.*;

class Gerbil
    {
    int gerbilNumber;
    Gerbil(int i)
        {
        gerbilNumber = i;
        }
    void hoop()
        {
        System.out.println("The gerbil can jump and its number is: " + gerbilNumber);
        }
    }

public class GerbilMaze2
    {
    static Map<String,Object> fill(Map<String,Object> m)
        {
        m.put("Rat2", new Gerbil(2));
        m.put("Rat1", new Gerbil(1));
        m.put("Rat3", new Gerbil(3));
        return m;
        }
    public static void main(String[] args)
        {
        Map<String,Object> gerbils = fill(new HashMap<String, Object>());
        System.out.println(gerbils.keySet());
        for (String k : gerbils.keySet())
            {
            gerbils.get(k).hoop();
            }
        }
    }

Everything seems pretty fine all the way down to the moment when I call the hoop() method. gerbils.get(k) is an object (when I println it, it's shows up as an object) but for some reason "cannot find symbol".

Thanks in advance for any help, Paul

You want Map<String,Gerbil> . There is no hoop method in Object .

(You might also be interested in Map.values and Map.entrySet .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM