Haxe - 对象作为地图的关键

Krz*_*cho 3 haxe

我正在尝试使用Object作为键来创建Map对象.问题是,当我尝试从这个地图中获取元素时,我总是得到null.因为关键是我不会给他确切的依据.我用同样的价值给予他对象,所以其他的依据.有什么方法可以解决这个问题吗?我可以交换一些'Equal'功能吗?

class PointInt
{
    public var x:Int;
    public var y:Int;

    ...
}
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的帮助.

npr*_*tto 9

正如解释这里这里 Map使用对象为重点的参考,你想用什么反而这样的一个HashMap中在haXe的作品:http://try.haxe.org/#7e048

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)';
    }
}
Run Code Online (Sandbox Code Playgroud)

您需要更改代码,除了使用HashMap而不是在密钥对象中haxe.ds.HashMap实现一个Map函数

由于您使用的是具有2个int的对象,并且hashmap只有1个int,因此2 PointInt将具有相同的哈希码,为了解决这个问题,您可以创建一个使用字符串作为哈希码的哈希映射但是如果可以的话写(或谷歌)一个很好的哈希函数你会得到更好的表现.