Java “.equals”和“==”有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1643067/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:36:27  来源:igfitidea点击:

What's the difference between ".equals" and "=="?

javaequals

提问by OVERTONE

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

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

So here's an example:

所以这是一个例子:

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

Instead of what I'm used to:

而不是我习惯的:

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

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

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

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

在快速搜索中找到了这个,但我真的无法理解这个答案:

采纳答案by Jon Skeet

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.

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

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

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

For example:

例如:

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!

Here xand yare references to the same string, because yis a compile-time constant equal to "hello".

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

回答by Sylar

The == operator compares if the objects are the same instance. The equals() oerator compares the state of the objects(e.g. if all attributes are equal). You can even override the equals() method to define yourself when an object is equal to another.

== 运算符比较对象是否为同一个实例。equals() 运算符比较对象状态(例如,如果所有属性都相等)。您甚至可以覆盖 equals() 方法来定义自己何时一个对象等于另一个对象。

回答by joel.neely

If you and I each walk into the bank, each open a brand new account, and each deposit $100, then...

如果你我每人走进银行,每人开一个全新的账户,每人存入 100 美元,那么……

  1. myAccount.equals(yourAccount)is truebecause they have the same value, but
  2. myAccount == yourAccountis falsebecause they are not the same account.
  1. myAccount.equals(yourAccount)true因为它们具有相同的值,但是
  2. myAccount == yourAccountfalse因为他们不是同一个帐号

(Assuming appropriate definitions of the Accountclass, of course. ;-)

Account当然,假设类的适当定义。;-)

回答by prashant

== is an operator. equals is a method defined in the Object class

== 是一个运算符。equals 是 Object 类中定义的方法

== checks if two objects have the same address in the memory and for primitive it checks if they have the same value.equals method on the other hand checks if the two objects which are being compared have an equal value(depending on how ofcourse the equals method has been implemented for the objects. equals method cannot be applied on primitives(which means that if a is a primitive a.equals(someobject) is not allowed, however someobject.equals(a) is allowed).

== 检查两个对象在内存中是否具有相同的地址,对于原语,它检查它们是否具有相同的值。另一方面,equals 方法检查正在比较的两个对象是否具有相等的值(取决于当然如何已经为对象实现了equals方法。equals方法不能应用于基元(这意味着如果a是基元,则不允许使用a.equals(someobject),但允许使用someobject.equals(a))。

回答by Jainendra

The equals( )method and the ==operator perform two different operations. The equals( )method compares the characters inside a Stringobject. The ==operator compares two object references to see whether they refer to the same instance. The following program shows how two different String objects can contain the same characters, but references to these objects will not compare as equal:

equals( )方法和==操作执行两种不同的操作。该equals( )方法比较String对象内的字符。该==运算符比较两个对象的引用,看看他们是否指的是同一个实例。下面的程序展示了两个不同的 String 对象如何可以包含相同的字符,但对这些对象的引用不会相等:

// equals() vs ==
class EqualsNotEqualTo {
     public static void main(String args[]) {
          String s1 = "Hello";
          String s2 = new String(s1);
          System.out.println(s1 + " equals " + s2 + " -> " +
          s1.equals(s2));
          System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
     }
}

The variable s1refers to the String instance created by “Hello”. The object referred to by s2is created with s1as an initializer. Thus, the contents of the two String objects are identical, but they are distinct objects. This means that s1and s2do not refer to the same objects and are, therefore, not ==, as is shown here by the output of the preceding example:

该变量s1指的是由“Hello”. 引用的对象 s2s1作为初始化程序创建的。因此,两个 String 对象的内容是相同的,但它们是不同的对象。这意味着s1ands2不引用相同的对象,因此, not ==,如前面示例的输出所示:

Hello equals Hello -> true
Hello == Hello -> false

回答by Jyoti Kumari

In Java, when the “==”operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. EX:

在 Java 中,当“==”运算符用于比较 2 个对象时,它会检查这些对象是否指向内存中的相同位置。前任:

String obj1 = new String("xyz");
String obj2 = new String("xyz");
if(obj1 == obj2)
   System.out.println("obj1==obj2 is TRUE");
else
  System.out.println("obj1==obj2 is FALSE");

Even though the strings have the same exact characters (“xyz”), The code above will actually output: obj1==obj2 is FALSE

即使字符串具有完全相同的字符(“xyz”),上面的代码实际上会输出: obj1==obj2 is FALSE

Java String class actually overrides the default equals()implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory. This means that if you call the equals() method to compare 2 String objects, then as long as the actual sequence of characters is equal, both objects are considered equal.

Java String 类实际上覆盖了Object 类中的默认equals()实现——并且它覆盖了该方法,以便它只检查字符串的值,而不是它们在内存中的位置。这意味着,如果调用 equals() 方法比较 2 个 String 对象,那么只要实际的字符序列相等,就认为两个对象相等。

String obj1 = new String("xyz");
String obj2 = new String("xyz");
if(obj1.equals(obj2))
   System.out.printlln("obj1==obj2 is TRUE");
else
  System.out.println("obj1==obj2 is FALSE");

This code will output the following:

此代码将输出以下内容:

obj1==obj2 is TRUE

obj1==obj2 为真

回答by Asif Ameer

Lets say that "==" operator returns true if both both operands belong to same object but when it will return true as we can't assign a single object multiple values

假设两个操作数都属于同一个对象,则“==”运算符返回 true,但何时返回 true,因为我们无法为单个对象分配多个值

public static void main(String [] args){
    String s1 = "Hello";
    String s1 = "Hello";  // This is not possible to assign multiple values to single object
    if(s1 == s1){
      // Now this retruns true
   }
}

Now when this happens practically speaking, If its not happen then why this is == compares functionality....

现在当这实际上发生时,如果它没有发生,那么为什么这是 == 比较功能....

回答by Ambrish Rajput

public static void main(String[] args){
        String s1 = new String("hello");
        String s2 = new String("hello");

        System.out.println(s1.equals(s2));
        ////
        System.out.println(s1 == s2);

    System.out.println("-----------------------------");

        String s3 = "hello";
        String s4 = "hello";

        System.out.println(s3.equals(s4));
        ////
        System.out.println(s3 == s4);
    }

Here in this code u can campare the both '==' and '.equals'

在此代码中,您可以同时使用 '==' 和 '.equals'

here .equals is used to compare the reference objects and '==' is used to compare state of objects..

这里.equals用于比较参考对象,'=='用于比较对象的状态..

回答by Suresh Giri

(1) == can be be applied for both primitives and object types, but equals() method can be applied for only object types.

(1) == 可以应用于基元类型和对象类型,但 equals() 方法只能应用于对象类型。

(2) == cannot be overridden for content comparison, but equals method can be overridden for content comparison(ex; String class, wrapper classes, collection classes).

(2) == 不能被内容比较覆盖,但是 equals 方法可以被内容比较覆盖(例如;String 类、包装类、集合类)。

(3) == gives incomparable types error when try to apply for heterogeneous types , where as equals method returns false.

(3) == 在尝试申请异构类型时会出现 incomparable types 错误,其中 as equals 方法返回 false。

回答by punitha

== operator compares two object references to check whether they refer to same instance. This also, will return true on successful match.for example

== 运算符比较两个对象引用以检查它们是否引用相同的实例。这也将在成功匹配时返回 true。例如

public class Example{
public static void main(String[] args){
String s1 = "Java";
String s2 = "Java";
String s3 = new string ("Java");
test(Sl == s2)     //true
test(s1 == s3)      //false
}}

above example == is a reference comparison i.e. both objects point to the same memory location

上面的例子 == 是一个引用比较,即两个对象都指向相同的内存位置

String equals() is evaluates to the comparison of values in the objects.

String equals() 被评估为对象中值的比较。

   public class EqualsExample1{
   public static void main(String args[]){
   String s = "Hell";
   String s1 =new string( "Hello");
   String s2 =new string( "Hello");
   s1.equals(s2);    //true
    s.equals(s1) ;   //false
    }}

above example It compares the content of the strings. It will return true if string matches, else returns false.

上面的例子它比较了字符串的内容。如果字符串匹配则返回真,否则返回假。