“.equals”之间的区别是什么?和“==”? [英] What's the difference between ".equals" and "=="?

查看:156
本文介绍了“.equals”之间的区别是什么?和“==”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天换了讲师,他说我用了一个奇怪的代码。 (他说最好使用 .equals 当我问为什么时,他回答因为它是!)

I switched lecturers today and he stated using a weird code to me. (He said it's better to use .equals and when I asked why, he answered "because it is!")

所以这是一个例子:

if (o1.equals(o2))
{
 System.out.println("Both integer objects are the same");
}

而不是我习惯的:

if (o1 == o2)
{
  System.out.println("Both integer objects are the same");
}

两者之间有什么区别。为什么他的方式(使用 .equals )更好?

What's the difference between the two. And why is his way (using .equals) better?

在快速搜索中发现这个但我无法理解这个答案:

Found this on a quick search but I can't really make sense of that answer:

推荐答案

在Java中, == 总是只比较两个引用(对于非原语,即) - 即它测试两个操作数是否引用同一个对象。

In Java, == always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.

然而,等于方法可以被覆盖 - 所以两个不同的对象仍然可以相等。

However, the equals method can be overridden - so two distinct objects can still be equal.

例如:

String x = "hello";
String y = new String(new char[] { 'h', 'e', 'l', 'l', 'o' });

System.out.println(x == y); // false
System.out.println(x.equals(y)); // true

此外,值得注意的是任何两个相等的字符串常量(主要是字符串文字,但也通过串联的字符串常量组合)最终将引用相同的字符串。例如:

Additionally, it's worth being aware that any two equal string constants (primarily string literals, but also combinations of string constants via concatenation) will end up referring to the same string. For example:

String x = "hello";
String y = "he" + "llo";
System.out.println(x == y); // true!

这里 x y 是对同一个字符串的引用,因为 y 是一个编译时常量,等于hello

Here x and y are references to the same string, because y is a compile-time constant equal to "hello".

这篇关于“.equals”之间的区别是什么?和“==”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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