[英]use of System.identityHashCode(obj) - when? why?
when would be a reasonable time to do line #4 instead of line #3? 何时合理的时间来做第4行而不是第3行? Or are they perfectly redundant invokes?
或者它们是完全冗余的调用?
1 Object o1 = new Object();
2
3 int hcObj = o1.hashCode();
4 int hcSys = System.identityHashCode(o1);
Sometimes you might want to create a set of distinguishable objects. 有时您可能想要创建一组可区分的对象。 Some of those objects may be equal to each other, but you still want references to all of them... only throwing away genuinely duplicate references.
其中一些对象可能彼此相同 ,但您仍然希望引用所有对象...只丢弃真正重复的引用。 You might do that because the
equals
implementation isn't the one you're interested in (some classes override equals
when you really don't want them to) or because you're actually just trying to count separate instances etc. 你可能会这样做,因为
equals
实现不是你感兴趣的实现(有些类在你真的不希望它们时覆盖equals
)或者你实际上只是想要计算单独的实例等。
To do that efficiently (ie backed by a hash table of some kind) you want a hash code based on identity rather than equality - which is exactly what identityHashCode
gives you. 为了有效地做到这一点(即由某种哈希表支持),你需要一个基于身份而不是相等的哈希码 - 这正是
identityHashCode
给你的。 It's rarely useful, but it can still be handy at times. 它很少有用,但它有时仍然很方便。
For a plain Object
, yes, it's redundant. 对于普通
Object
,是的,它是多余的。 But there are cases where a class might want to use the default hashCode
implementation (based on reference equality) on an instance of a type that could have overridden hashCode
. 但是有些类可能希望在可能重写
hashCode
的类型的实例上使用默认的hashCode
实现(基于引用相等性)。
Grepcode lists these call sites , namely including IdentityHashMap
amongst others. Grepcode 列出了这些调用站点 ,包括
IdentityHashMap
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.