“有什么区别?”=”和“= =”?(复制)

时间:2022-05-11 22:29:07

This question already has an answer here:

这个问题已经有了答案:

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!")

我今天换了讲师,他给我写了一段奇怪的代码。(他说最好使用。等于,当我问为什么时,他回答“因为它是!”)

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?

两者的区别是什么?为什么他的方法更好?

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

在快速搜索中发现了这个问题,但我无法真正理解这个答案:

11 个解决方案

#1


110  

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 equals method 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 x and y are references to the same string, because y is a compile-time constant equal to "hello".

这里x和y是同一个字符串的引用,因为y是一个编译时的常数,等于“hello”。

#2


19  

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() oerator比较对象的状态(例如,如果所有属性都是相等的)。您甚至可以重写equals()方法来定义自己,当一个对象等于另一个对象时。

#3


15  

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 true because they have the same value, but
  2. myAccount.equals(yourAccount)是正确的,因为它们的值相同,但是。
  3. myAccount == yourAccount is false because they are not the same account.
  4. 我的账户是假的,因为它们不是同一个账户。

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

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

#4


2  

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

= =操作符。equals是在对象类中定义的方法。

== 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)是允许的)。

#5


0  

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

==操作符比较两个对象引用,以检查它们是否引用相同的实例。这也会在成功的比赛中重现。例如

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.

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

#6


-1  

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中,当“==”操作符用于比较两个对象时,它会检查对象是否在内存中引用相同的位置。例:

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是错误的。

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类实际上覆盖了对象类中的默认equals()实现——它重写了这个方法,这样它只检查字符串的值,而不是只检查它们在内存中的位置。这意味着如果您调用equals()方法来比较两个字符串对象,那么只要字符的实际序列是相等的,那么这两个对象都是相等的。

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 = = methoda是正确的

#7


-1  

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'

在这段代码中,u可以表示“==”和“。等于”

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

这里。equals用于比较引用对象和'=='用于比较对象的状态。

#8


-1  

(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方法重写为内容比较(ex;String类,包装类,集合类)。

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

(3)==在尝试应用异类类型时给出了不可比拟的类型错误,当equals方法返回false时。

#9


-2  

The equals( ) method and the == operator perform two different operations. The equals( ) method compares the characters inside a String object. 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()方法比较字符串对象中的字符。操作符比较两个对象引用,看它们是否引用相同的实例。下面的程序展示了两个不同的字符串对象如何包含相同的字符,但是对这些对象的引用将不会被比较:

// 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 s1 refers to the String instance created by “Hello”. The object referred to by s2 is created with s1 as an initializer. Thus, the contents of the two String objects are identical, but they are distinct objects. This means that s1 and s2 do not refer to the same objects and are, therefore, not ==, as is shown here by the output of the preceding example:

变量s1引用由“Hello”创建的字符串实例。s2所引用的对象是用s1作为初始化器创建的。因此,两个字符串对象的内容是相同的,但它们是不同的对象。这意味着s1和s2不引用相同的对象,因此,not ==,如前面示例的输出所示:

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

#10


-2  

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

现在,当这一切发生的时候实际上,如果它不会发生那么为什么这是.... = =比较功能

#11


-2  

Here is a simple interpretation about your problem:

以下是对你的问题的简单解释:

== (equal to) used to evaluate arithmetic expression

==(等于)用于计算算术表达式。

where as

equals() method used to compare string

equals()方法用于比较字符串。

Therefore, it its better to use == for numeric operations & equals() method for String related operations. So, for comparison of objects the equals() method would be right choice.

因此,使用==为字符串相关操作的数值操作& equals()方法更好。因此,对于对象的比较,equals()方法是正确的选择。

#1


110  

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 equals method 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 x and y are references to the same string, because y is a compile-time constant equal to "hello".

这里x和y是同一个字符串的引用,因为y是一个编译时的常数,等于“hello”。

#2


19  

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() oerator比较对象的状态(例如,如果所有属性都是相等的)。您甚至可以重写equals()方法来定义自己,当一个对象等于另一个对象时。

#3


15  

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 true because they have the same value, but
  2. myAccount.equals(yourAccount)是正确的,因为它们的值相同,但是。
  3. myAccount == yourAccount is false because they are not the same account.
  4. 我的账户是假的,因为它们不是同一个账户。

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

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

#4


2  

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

= =操作符。equals是在对象类中定义的方法。

== 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)是允许的)。

#5


0  

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

==操作符比较两个对象引用,以检查它们是否引用相同的实例。这也会在成功的比赛中重现。例如

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.

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

#6


-1  

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中,当“==”操作符用于比较两个对象时,它会检查对象是否在内存中引用相同的位置。例:

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是错误的。

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类实际上覆盖了对象类中的默认equals()实现——它重写了这个方法,这样它只检查字符串的值,而不是只检查它们在内存中的位置。这意味着如果您调用equals()方法来比较两个字符串对象,那么只要字符的实际序列是相等的,那么这两个对象都是相等的。

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 = = methoda是正确的

#7


-1  

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'

在这段代码中,u可以表示“==”和“。等于”

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

这里。equals用于比较引用对象和'=='用于比较对象的状态。

#8


-1  

(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方法重写为内容比较(ex;String类,包装类,集合类)。

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

(3)==在尝试应用异类类型时给出了不可比拟的类型错误,当equals方法返回false时。

#9


-2  

The equals( ) method and the == operator perform two different operations. The equals( ) method compares the characters inside a String object. 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()方法比较字符串对象中的字符。操作符比较两个对象引用,看它们是否引用相同的实例。下面的程序展示了两个不同的字符串对象如何包含相同的字符,但是对这些对象的引用将不会被比较:

// 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 s1 refers to the String instance created by “Hello”. The object referred to by s2 is created with s1 as an initializer. Thus, the contents of the two String objects are identical, but they are distinct objects. This means that s1 and s2 do not refer to the same objects and are, therefore, not ==, as is shown here by the output of the preceding example:

变量s1引用由“Hello”创建的字符串实例。s2所引用的对象是用s1作为初始化器创建的。因此,两个字符串对象的内容是相同的,但它们是不同的对象。这意味着s1和s2不引用相同的对象,因此,not ==,如前面示例的输出所示:

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

#10


-2  

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

现在,当这一切发生的时候实际上,如果它不会发生那么为什么这是.... = =比较功能

#11


-2  

Here is a simple interpretation about your problem:

以下是对你的问题的简单解释:

== (equal to) used to evaluate arithmetic expression

==(等于)用于计算算术表达式。

where as

equals() method used to compare string

equals()方法用于比较字符串。

Therefore, it its better to use == for numeric operations & equals() method for String related operations. So, for comparison of objects the equals() method would be right choice.

因此,使用==为字符串相关操作的数值操作& equals()方法更好。因此,对于对象的比较,equals()方法是正确的选择。