0

I am new to Java Programming and Hashmaps and I have a problem that I need help with.

I have a Hashmap that stores a collection of objects:

private HashMap <String, Turtle> turtles = new HashMap<String, Turtle>();

I also have a collection of shapes which I have added to the Turtle class:

ArrayList<String> shapes = new ArrayList<String>();

What I am trying to do is find a way so that it adds the shape object with a specified name to the turtle object with a specified name by passing the parameters of String turtleName and String shapeName.

I do not know how to go about this with a ArrayList and a Hashmap.

3
  • 2
    There are no shape objects. The ArrayList contains Strings. Commented May 17, 2014 at 20:36
  • If you don't know how to do it write sudo code here to explain what you want to do. Commented May 17, 2014 at 21:16
  • Please give an example of one of your "shape objects" (which seem to be just strings) Commented May 17, 2014 at 21:20

1 Answer 1

1

As I understood your question, what you need to do is:

  1. Getting the corresponding Turtle in the Map using the turtleName key
  2. Getting the List for this Turtle and add the shapeName to the List

Which can be translated in Java code too:

public void addShapeNameToTurtle(String turtleName, String shapeName){
    turtles.get(turtleName).getList().add(shapeName);
}

where getList() returns the shapes associated with the current Turtle's instance.

A prefered way would be to add an addShapeName method to your Turtle class (which will add the String you pass in parameter to the List), then the call would be simplified to turtles.get(turtleName).addShapeName(shapeName);

You will also have to check that the mapping exists in the map and that the List is not null when getting it.

Also you should read the Javadoc of both classes to have an overview of the availables methods for both classes:

Sign up to request clarification or add additional context in comments.

1 Comment

Apologies for the late answer, but thank you for your help! This worked for what I was trying to achieve, sorry everyone about how vaguely I had put the question; in the future, I'll try and be more specific!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.