如何使用两个数字作为地图键 [英] How to use two numbers as a Map key
本文介绍了如何使用两个数字作为地图键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个数字,我想将它们一起用作 Map
中的键。目前,我连接他们的字符串表示。例如,假设键编号是4和12.我使用:
I have two numbers and I want to use them together as a key in a Map
. Currently, I'm concatenating their string representations. For example, suppose the key numbers are 4 and 12. I use:
String key = 4 + "," + 12;
地图被声明为 Map< String,Object>
。
我认为这太糟了!我喜欢使用 String
之外的其他键作为键!我想要最快的方式来创建这些键。
I think this is so bad! I like to use something other than a String
as the key! I want the fastest way to create these keys.
谁有好主意?
推荐答案
创建一个包含两个数字并将其用作键的对象。例如:
Create an object that holds the two numbers and use it as the key. For example:
class Coordinates {
private int x;
private int y;
public Coordinates(int x, int y) {
...
}
// getters
// equals and hashcode using x and y
}
Map<Coordinates, Location> locations = new HashMap<Coordinates, Location>();
如果您喜欢使用数学方法,请参阅 This StackOverflow answer 。
If you prefer a mathematical approach, see this StackOverflow answer.
这篇关于如何使用两个数字作为地图键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文