iDeveloper
iDeveloper

Reputation: 1725

Storing multiple datatypes in a single HashMap

I want to put an array of int and a String into a HashMap. Is this possible? what is the proper way to that?

This is my HashMap:

Map<String, String> stringMap = new HashMap<>();

    stringMap.put("Text","fish" );
    stringMap.put("Diet","false");
    stringMap.put("CookingTime", "60");
    stringMap.put("OptionId", [7,8,8]);

I know this line is wrong - how do I store an array in a HashMap?

    stringMap.put("OptionId", [7,8,8]);

Upvotes: 1

Views: 639

Answers (1)

Chris
Chris

Reputation: 2465

You can instantiate an array in java by doing

someMap.put("OptionId", new int[]{7,8,8});

Otherwise you will need a function that returns those values in an array.

For your case: if you want to create a HashMap of multiple datatypes you can use

HashMap<String, Object> map = new HashMap<String, Object>();

You can then put anything you want in

map.put("key1", "A String");
map.put("key2",  new int[]{7,8,8});
map.put("key3", 123);

Except now the tricky part is you don't know what is what so you need to use instanceof to parse the map unless you know what type of object is at a key then you can just cast it to that type.

if(map.get("key1") instanceof String)
    String s = (String) map.get("key1"); // s = "A String"

or

int[] arr = (int[]) map.get("key2"); // arr = {7,8,8}

Upvotes: 4

Related Questions