要比较UUID,可以使用==还是必须使用UUID.equals(UUID)? [英] To compare UUID, can I use == or have to use UUID.equals(UUID)?

查看:104
本文介绍了要比较UUID,可以使用==还是必须使用UUID.equals(UUID)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只需开始使用 java.util.UUID .我的问题是,如果我有两个UUID变量,例如u1和u2,并且我想检查它们是否相等,我可以安全地使用表达式 u1 == u2 还是必须编写 u1.equals(u2)?假设两者都不为空.

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.

顺便说一句,我正在使用其 randomUUID 方法创建新的UUID值,但是我认为这无关紧要.我想知道UUID是唯一的,每个值都可以是一个单例,那么使用 u1 == 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.

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
   }
}

推荐答案

这取决于:您想要哪种平等类型?

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 是同一对象时,

a == b 是true.如果它们是两个相同的对象,它将仍然是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.equals(b)为true.

这篇关于要比较UUID,可以使用==还是必须使用UUID.equals(UUID)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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