Using objects as Map keys in Haxe

时光怂恿深爱的人放手 提交于 2019-12-06 00:59:19
npretto

As explained here and here, Map in Haxe works using the reference of the object as the key.

What you want to use instead is a HashMap like this (try.haxe link):

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)';
    }
}

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

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!