javamethodshashmapkeyset

In class A, I want to go throught the keySet of a HashMap in class B


I want to go through each key in a keySet of a HashMap from another class. Right now this is what I have:

Admin.java

import java.util.HashMap

public class Admin {
public static HashMap<String, Person> person = new HashMap<String, Person>();

    public static void main (String [] args) {
         for (String key: person.get("James").getHashMap().keySet()) {
         System.out.println(key);
    }

}

Person.java

import java.util.HashMap

public class Person {
public static HashMap<String, Book> book = new HashMap<String, Book>();
private static String title = "";


    public Book (String titleIn) {
         title = titleIn;
    }

    public HashMap getHashMap(){
         return book;
    }


}

I think I can't do this beacause I am unable to use HashMap commands on a HashMap that isn't stored in the same class.

Is there another method I could use? Am I calling it wrong from Admin.java?

Thanks!


Solution

  • Your getHashMap method returns a raw HashMap in your Person class.

    Raw maps are not parametrized, so the type for their key is Object implicitly.

    You need to change it to:

    public Map<String, Book> getHashMap(){
       return book;
    }
    

    ... in order to be able to reference a key as String.

    Edit

    You also need to either change the book variable to instance (as opposed to static), or make the getHashMap method static.

    The latter is probably advised against, as it would return the same object for all your Person instances.