“.equals"和“.equals"有什么区别?和“=="? [英] What's the difference between ".equals" and "=="?

查看:44
本文介绍了“.equals"和“.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.

但是,equals 方法可以被覆盖 - 因此两个不同的对象仍然可以相等.

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!

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

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

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

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