0

I have a map with integer keys and corresponding values of arrays of strings. I want to get a get a value out of that array from inside the map and am having a heck of a time doing this. My searches haven't yielded anything useful other than the recommendation to 'wrap it' and I'm really not sure what that means! Here is an example:

Map myTasks = new HashMap();

myTasks.put(1, new String[] {"cake"});
myTasks.put(15, new String[] {"bake"});

String myString = myTasks.get(1)[0];  // This doesn't work.

So I have picked up that myTasks.get(1) returns an object. How do I get a string value out of that object?

Thank you!

3 Answers 3

2

You can also use Generics for it:

public static void main(String[] args) {
    Map<Integer, String[]> myTasks = new HashMap<Integer, String[]>();

    myTasks.put(1, new String[] {"cake"});
    myTasks.put(15, new String[] {"bake"});

    String myString = myTasks.get(1)[0];
    System.out.println(myString);
}
Sign up to request clarification or add additional context in comments.

Comments

2

Problem in your code is, you are trying to access an object as array directly.

Try this-

Map myTasks = new HashMap();

myTasks.put(1, new String[] {"cake"});
myTasks.put(15, new String[] {"bake"});

String[] myString = (String[]) myTasks.get(1);
System.out.println(myString[0]);

All you have to do is typecast the object.

Best practice is to use-

Map<Integer, String[]> myTasks = new HashMap<Integer, String[]>();

Instead of Map myTasks = new HashMap(); with which you don't need to typecast.

Comments

1

Add generic type:

Map<Integer, String[]> myTasks = new HashMap<Integer, String[]>();

Comments

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.