Scala 对象的唯一 ID [英] Unique id for Scala object

查看:95
本文介绍了Scala 对象的唯一 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,id(x) 给出对象 x 的唯一 id.Scala 中的等价物是什么?

<预><代码>>>>身份证(真)1166096>>>身份证(假)1166108>>>x = id([1,2,3])>>>编号(x)2058589988>>>y = id([1,2,3])>>>编号(y)2058589976

我可以使用 x.hashCode 作为 id,但是当内容相同时它会返回相同的值.我想知道是什么让以下代码中的 a eq b == false .a eq b 中比较了哪些值?

scala>val a = ArrayBuffer(1,2,3)a: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3)标度>val b = ArrayBuffer(1,2,3)b: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3)标度>a.hashCoderes44:整数 = 387518613标度>b.hashCoderes45:整数 = 387518613标度>等式res39:布尔值 = 假

解决方案

这是不可能的.您需要自己生成并跟踪 ID.

eq 比较引用,类似于Java中的==.

System.identityHashCode(这是Any.hashCode的默认实现),但不保证唯一.

您可以使用 JNI 实现 id,尽管由于压缩 GC 的可能性,它可能不是微不足道的.不过,我对 JNI 了解不多.

即便如此,我也不认为 id 是一个有用的函数,我也没有看到 任何 使用它.如果需要对对象的引用,请存储引用.如果您需要弱引用,请使用 java.lang.ref.WeakReference[T].

In Python, id(x) gives the unique id of object x. What's the equivalence in Scala?

>>> id(True)
1166096
>>> id(False)
1166108
>>> x = id([1,2,3])
>>> id(x)
2058589988
>>> y = id([1,2,3])
>>> id(y)
2058589976

I could use x.hashCode for the id, but it will return the same value when the contents are the same. I'd like to know what makes a eq b == false in the following code. What values are compared in a eq b?

scala> val a = ArrayBuffer(1,2,3)
a: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3)

scala> val b = ArrayBuffer(1,2,3)
b: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3)

scala> a.hashCode
res44: Int = 387518613

scala> b.hashCode
res45: Int = 387518613

scala> a eq b
res39: Boolean = false

解决方案

It is not possible to do this. You need to generate and keep track of IDs yourself.

eq compares references, and is similar to == in Java.

There is System.identityHashCode (which is the default implementation of Any.hashCode) but it is not guaranteed to be unique.

You may be able to implement id using the JNI, although it might not be trivial due to the possibility of a compacting GC being in place. I don't know much about the JNI, though.

Even then, I don't see id as a useful function and I don't see any use for it. If you need a reference to an object, store a reference. If you need a weak reference, use a java.lang.ref.WeakReference[T].

这篇关于Scala 对象的唯一 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆