0

I'm learning how to use hashmaps and I'm having some issues here. I created two classes called Zoo and Animals, and I joined both classes using an Hashmap:

private HashMap<Zoo, Animals> zoo;

I built a method to add data into the hashmap:

public void setAnimal(Zoo zoo, Animals animal ){
    zoo.put(zoo, animal);
}

And I'm inserted the follwing values into the hashmap:

   Main main = new Main();

   Zoo zoo1 = new Zoo("France", 1);
   Zoo zoo2 = new Zoo("Spain", 2);

   Animals gorilla = new Animals(2015, "Gorilla");
   Animals frog = new Animals(2018, "Frog");

   Animals zebra = new Sedan(2016, "zebra");
   Animals lion= new Sedan(2016, "lion");

   main.setAnimal(zoo1, gorilla);
   main.setAnimal(zoo2, frog);

   main.setAnimal(zoo2, lion);
   main.setAnimal(zoo2, zebra);

And I built a method to print the Zoos and the respective animals in there:

 String text = "";

        for(Map.Entry<Zoo, Animals> entry : zoo.entrySet()) {

            Zoo key = entry.getKey();
            Animals value = entry.getValue();

            text += key.toString() + "\n";

            text += value.toString() + "\n";


        }

        return text;

But I just get this:

France 1 
gorilla

Spain 2 
Zebra

Instead of

France 1
Gorilla

Spain 2
frog
lion
zebra

How can I get the full animals list?

Banha Dix
  • 113
  • 1
  • 10
  • Basically, the second parameter, `Animals` needs to be a list of animals rather than just one animal: `>`. – markspace Mar 19 '18 at 21:52
  • `Map` maps a key to a *single* value. If you keep on calling `put` for the same key, you overwrite the previous value. – Andy Turner Mar 19 '18 at 21:52
  • A map that returns multiple values is sometimes called a Multi-Map. Apache commons has one, though the standard Java API does not: https://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/MultiMap.html – markspace Mar 19 '18 at 22:06

0 Answers0