Java 要比较 UUID,我可以使用 == 还是必须使用 UUID.equals(UUID)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23589058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
To compare UUID, can I use == or have to use UUID.equals(UUID)?
提问by Newyacht Zhang
Just start using java.util.UUID
. My question is if I have two UUID variables, say u1 and u2, and I would like to check if they are equal, can I safely use expression u1 == u2
or have to write u1.equals(u2)
? assuming both are not null.
刚开始使用java.util.UUID
。我的问题是,如果我有两个 UUID 变量,比如 u1 和 u2,我想检查它们是否相等,我可以安全地使用表达式u1 == u2
还是必须写u1.equals(u2)
?假设两者都不为空。
BTW, I am using its randomUUID
method to create new UUID values, but I think this should not be matter.
I wonder as UUID is unique, each value could be a singleton, then it is safe to use u1 == u2
.
顺便说一句,我正在使用它的randomUUID
方法来创建新的 UUID 值,但我认为这应该无关紧要。我想知道 UUID 是唯一的,每个值都可以是一个单例,那么使用u1 == u2
.
void method1(UUID u1, UUID u2) {
// I know it is always safe to use equal method
if (u1.equals(u2)){
// do something
}
// is it safe to use ==
if (u1 == u2) {
// do something
}
}
采纳答案by user253751
It depends: which type of equality do you want?
这取决于:您想要哪种类型的平等?
UUID a = new UUID(12345678, 87654321);
UUID b = new UUID(12345678, 87654321);
UUID c = new UUID(11111111, 22222222);
System.out.println(a == a); // returns true
System.out.println(a.equals(a)); // returns true
System.out.println(a == b); // returns false
System.out.println(a.equals(b)); // returns true
System.out.println(a == c); // returns false
System.out.println(a.equals(c)); // returns false
a == b
is true only if a
and b
are the same object. If they are two identical objects, it will still be false.
a == b
仅当a
和b
是同一个对象时才为真。如果它们是两个相同的对象,它仍然是假的。
a.equals(b)
is true if a
and b
are the same UUID value - if their two parts are the same.
a.equals(b)
如果a
和b
是相同的 UUID 值 - 如果它们的两个部分相同,则为真。
回答by Makoto
Well...no.
嗯……不。
==
against an object checks for reference equality. That is, it checks to see if these two objects are literally the same spot in memory.
==
针对对象检查引用相等性。也就是说,它会检查这两个对象是否在内存中实际上是同一个位置。
.equals()
will check for actual object equivalence. And, the Javadoc for UUID
goes into great detail to explain when two UUID
instances are equivalent.
.equals()
将检查实际的对象等效性。并且,Javadoc forUUID
非常详细地解释了何时两个UUID
实例是等效的。