在Haxe中将对象用作Map键 [英] Using objects as Map keys in Haxe
问题描述
我正在尝试使用对象作为键来创建Map
.问题是,当我尝试从该地图中获取元素时,总是得到null
.这是因为我没有提供与键完全相同的参考.我提供的对象具有相同的值,因此引用不同.
I'm trying to make a Map
with an object as a key. The problem is, that when I try to get elements from this map, I always get null
. It's because I'm not providing the exact same reference as the key was. I'm providing an object with the same values, so the reference is different.
有什么办法可以解决这个问题?我可以使用某种equals()
函数吗?
Is there any way to solve that? Can I make it use some kind of equals()
function?
class PointInt
{
public var x:Int;
public var y:Int;
...
}
var map = new Map<PointInt, Hex>();
var a = new PointInt(1, 1);
var b = new PointInt(1, 1);
var hex_a = new Hex();
map[a] = hex_a;
var hex_b = map[b];
/// hex_b == null now because reference(a) == reference(b)
推荐答案
如此处所述和此处,Map
在Haxe中,使用对象的引用作为关键.
As explained here and here, Map
in Haxe works using the reference of the object as the key.
您要使用的是 HashMap
( try.haxe链接):
import haxe.ds.HashMap;
class Test {
static function main() {
var map = new HashMap();
map.set(new PointInt(1, 1), 1);
trace(map.get(new PointInt(1,1)));
}
}
class PointInt
{
public var x:Int;
public var y:Int;
public function new(x:Int, y:Int)
{
this.x = x;
this.y = y;
}
public function hashCode():Int
{
return x + 1000*y; //of course don't use this, but a real hashing function
}
public function toString()
{
return '($x,$y)';
}
}
除了使用haxe.ds.HashMap
代替Map
之外,您需要在代码中进行的更改是在关键对象中实现hashCode : Void->Int
函数
What you need to change in your code, besides using haxe.ds.HashMap
instead of Map
is to implement a hashCode : Void->Int
function in your key object
由于您使用的对象具有2个整数,并且哈希映射仅为1个整数,因此2 PointInt
将具有相同的哈希码.为了解决这个问题,您可以创建一个使用字符串作为哈希码的哈希映射,但是如果您可以编写(或Google)一个好的哈希函数,您将获得更好的性能.
Since you're using an object that has 2 ints, and the hash map is just 1 int, it will happen that 2 PointInt
will have the same hash code. To solve this you could create a hash map that uses strings as hashcode but if you can write (or google) a good hash function you will get better performance.
这篇关于在Haxe中将对象用作Map键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!