Ellie
Ellie

Reputation: 27

How do I reference an object that is a type in a java map?

I am a beginner and am stuck. I have a Map which is of type String, Object. Once I have declared it:

Map<String, Fish> fishes = new HashMap<String, Fish>();

what do I do now. How do I get my values into the fish object - I am stuck about how to reference the fish object. I know I should use 'get', but everything I try doesn't work.

Apologies, I know this is simpleton stuff, but help would be really appreciated.

Upvotes: 0

Views: 135

Answers (4)

Alex Moore
Alex Moore

Reputation: 3455

Looks like you may be having some trouble with syntax, try this:

Map<String, Fish>  fishes = new HashMap<String, Fish>();

After that, you can use get and put to get items in and out of the HashMap.

Java HashMap Documentation

Upvotes: 0

Bill
Bill

Reputation: 2633

Map<String, Fish> fishes = new HashMap<String, Fish>();

To get all your fishes...

for (String key : fishes.keySet()) {
    Fish fish = fishes.get(key);
}

Upvotes: 0

Mike
Mike

Reputation: 8545

First off your declaration is a bit off, it should be:

Map <String, Fish>  fishes = new HashMap <String, Fish> ();

To add values into it you would have code that looks like

Fish trout = new Fish();
fishes.put("trout",trout);

To get the Fish at key "trout" you access it with the get like this:

fishes.get("trout");

Which returns the Fish object at the key "trout"

Upvotes: 1

lukastymo
lukastymo

Reputation: 26809

//creating new Fish object - no big deal
Fish fish = new Fish();
//putting fish to map
fishes.put("MyFish", fish);
//getting your fish
Fish myFish = fishes.get("MyFish");

Upvotes: 0

Related Questions