在单个HashMap中存储多个数据类型

时间:2022-07-21 21:17:29

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

我想将一个int数组和一个String放入HashMap中。这可能吗?什么是正确的方法?

This is my HashMap:

这是我的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?

我知道这行是错误的 - 如何在HashMap中存储数组?

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

1 个解决方案

#1


2  

You can instantiate an array in java by doing

您可以通过执行实例化java中的数组

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

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.

除了现在棘手的部分是你不知道什么是什么所以你需要使用instanceof来解析地图,除非你知道什么类型的对象在一个键,然后你可以将它转换为该类型。

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}

#1


2  

You can instantiate an array in java by doing

您可以通过执行实例化java中的数组

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

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.

除了现在棘手的部分是你不知道什么是什么所以你需要使用instanceof来解析地图,除非你知道什么类型的对象在一个键,然后你可以将它转换为该类型。

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}