【发布时间】:2013-01-24 11:13:51
【问题描述】:
让我们从代码开始。
Future<MyResult> obj = getFuture();
debugLog.println("Handling future: " + System.identityHashCode(obj);
然后在其他地方再次相同,或者可能再次执行同一段代码,可能在不同的线程中。
Future<MyResult> obj = getFuture();
debugLog.println("Handling future: " + System.identityHashCode(obj);
现在上面,如果 obj 是同一个对象,调试打印将是相同的,很明显。但是如果它们不同,仍然有可能发生哈希冲突,因此即使对于不同的对象,打印输出可能也是相同的。所以具有相同的输出(或更一般地说,相同的字符串)并不能保证相同的对象。
问题:在 Java 中有没有办法为任意对象获取唯一的 id string?或者更正式地说,给出static String Id.str(Object o) 方法,这样总是为真:
final Object obj1 = ...;
final String firstId = Id.str(obj1);
// arbitrary time passes, garbage collections happen etc.
// firstId and obj1 are same variables as above
(firstId.equals(Id.str.obj2)) == (obj1 == obj2)
【问题讨论】:
标签: java object identity uniqueidentifier