具有多个值键的HashMap [英] HashMap with multiple valued keys

查看:88
本文介绍了具有多个值键的HashMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建一个键为整数数组的HashMap?

Is it possible to create a HashMap whose key is an array of integers?

我习惯于使用Python,最近我开始使用Java.在我的工作中,我需要使用以下键创建一个HashMap:

I´m accustomed to use Python and just recently I began working with Java. In my job I need to create a HashMap with keys like:

map.put([5,2], 1);
map.put([3,2], 0);

,依此类推.我正在使用它来稍后测试地图中是否存在一对数字,如果是,则执行某些操作,如果不存在,请继续.

and so on. I´m using it to later on test if a pair of those numbers are present in the map, if yes, then do something, if not, continue.

为此,我尝试了以下操作:

To do so I tried the following:

Map<Array, Boolean> test = new HashMap<Array, Boolean>();
int[] a1 = {5,2};
test.put(a1, true);

Eclipse给出消息(参数不适用于int [] ...").但是我完成的任何配置都会出现一些错误.

Eclipse gives the message ("The arguments are not applicable to int[]..."). But any configuration I´ve done I get some error.

我尝试使用ArrayList,地图内的对象,嵌套的HashMap等,但都无济于事(在python中,这很简单,我只写dict [(5,2)] = 1,所以我想Java就是这样简单的东西.建议我将数字转换为字符串,然后在其间添加一个冒号,例如:

I tried using ArrayList, Objects inside the map, nested HashMap and so on but none worked (in python it´s very easy, I´d just write dict[(5,2)] = 1, so I imagine in Java there´s something simple like that). I was suggested to transform the numbers into Strings and add a colon between then, like:

map.put("5:2", 1);

然后我再次打破字符串,但是如果这是解决方案,我将回到Python;)!!

and later on I break the string again but if this is the solution I´ll go back to Python ;)!!

可能这是一个非常简单的问题,但我找不到答案,希望您能为我提供帮助.

Probably this is a very simple question but I couldn´t find the answer, hope you can help me.

提前谢谢!

推荐答案

如果要检查条目的存在,可以使用

If you want to check for the existance of your entry, you can use a Set (a useful concrete implementation is HashSet.

final Set<List<Integer>> population;

population = new HashSet<List<Integer>>();
population.add(Arrays.asList(1, 2));

if (population.contains(Arrays.asList(1, 2)))
{
  ...
}

您可以像上面所做的那样使用List-但这不能保证您所有列表的长度都恰好是两个元素(如果确实是一个约束).为了使其更加健壮,您可以创建自己的类来表示元组.如果这样做,请确保实现 equals() hashCode() (这是一个解释良好做法的文章).

You can use an List as I have done above - but that doesn't guarantee that all your lists are exactly two elements long (if that is indeed a constraint). To make it a bit more robust, you could create your own class to represent the tuple. If you do, make sure you implement equals() and hashCode() (here's an article explaining good practice).

Arrays.asList() 是在代码中内联创建列表的有用方法.更一般的列表是 ArrayList

这篇关于具有多个值键的HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆