I'm trying to call the values of the hashmap from another method. I need the values 1, "Twin", 200, 200
to be printed instead of "YES"
when TW
has been called in ref
. However keep in mind I have to leave setupMuseum
as private
. I've tried different approaches but each time ended up with an error.
private void setupMuseum() {
HashMap<String, MUSEUM>Museum= new HashMap<String, MUSEUM>();
Museum.put("TW", new MUSEUM(1, "Twin", 200, 200));
}
public String getMuseumDetails(String ref) {
if ("TW".equals(ref) ){
System.out.println("YES");
}else
return "!";
return "\nNo such thing";
}
CodePudding user response:
Your setupMuseum()
method is useless as is. It creates a Map
that is not even returned and which is also not an instance variable. You need to return the created Map
and then you can print whatever is in there:
private Map<String, MUSEUM> setupMuseum() {
HashMap<String, MUSEUM> Museum = new HashMap<String, MUSEUM>();
Museum.put("TW", new MUSEUM(1, "Twin", 200, 200));
return Museum;
}
Then in your getMuseumDetails()
method, you need to call setupMuseum()
and print the values:
public String getMuseumDetails(String ref) {
if ("TW".equals(ref) ){
HashMap<String, MUSEUM> museum = getMuseumDetails();
System.out.println(museum.get("TW"));
} else {
return "!";
}
return "\nNo such thing"; // This is unreachable
}
This is assuming that both methods are in the same file, so that setupMuseum()
can be reached within getMuseumDetails()
. This also assumes that your MUSEUM
class has an appropriate toString()
implementation that actually includes all its properties.
As side notes please keep the following in mind:
- Usually, variables in Java follow snakeCase, so you should name
Museum
asmuseum
. - Java classes should not have their name as uppercase, so you should name
MUSEUM
asMuseum
. - You should strive to use Java interfaces instead of concrete implementations. This means that you should use
Map<String, MUSEUM> Museum = new HashMap<String, MUSEUM>();
instead ofHashMap<String, MUSEUM> Museum = new HashMap<String, MUSEUM>();
so that you declare the variable as aMap
(the interface) instead of as aHashMap
(the concrete implementation).