Reputation: 27
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
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.
Upvotes: 0
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
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
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