【问题标题】:Using objects as Map keys in Haxe在 Haxe 中使用对象作为 Map 键
【发布时间】:2014-12-09 01:32:00
【问题描述】:

我正在尝试使用对象作为键创建Map。问题是,当我尝试从这张地图中获取元素时,我总是得到null。这是因为我没有提供与密钥完全相同的参考。我提供了一个具有相同值的对象,所以引用不同。

有什么办法可以解决吗?我可以让它使用某种equals() 函数吗?

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)

【问题讨论】:

    标签: haxe


    【解决方案1】:

    正如here 和here 所解释的,Haxe 中的Map 使用对象的引用作为键来工作。

    您想改用这样的HashMap (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)';
        }
    }
    

    除了使用haxe.ds.HashMap 而不是Map 之外,您需要在代码中更改的是在您的关键对象中实现hashCode : Void-&gt;Int 函数

    由于您使用的对象具有 2 个整数,而哈希映射只有 1 个整数,因此 2 PointInt 将具有相同的哈希码。为了解决这个问题,您可以创建一个使用字符串作为哈希码的哈希映射,但是如果您可以编写(或 google)一个好的哈希函数,您将获得更好的性能。

    【讨论】:

    • 所以我现在所做的是将 ObjectMap 更改为 ObjectMap。我已经为 PointInt 类中的字符串创建了一些简单的散列函数。它很慢,但它做了它必须做的事情。也许有一天会有其他选择。 =]
    • 是否可能需要 hashCode 函数来为不同的对象产生唯一的结果? try.haxe.org/#B753E 据我了解,HashMap 应该使用 hashCode 函数进行分桶,而不是区分对象。
    猜你喜欢
    • 1970-01-01
    • 2015-12-16
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    • 2022-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多