python 和 java == 运算符有什么区别

What is the difference between python and java == operator

有人可以向我解释为什么 Python 能够打印下面的语句而 Java 不能。我知道这与 Java 和 equals() 中的 == 有关,但我不太明白其中的区别。

Python代码

str1 = "Pro"
str2 = str1 + ""

if str1 == str2:
   print("the strings are equal")```

Java代码

public class StringEq {
    public static void main(String[] args) {
        String str1 = "Pro";
        String str2 = str1 + "";

       if (str1 == str2) {
            System.out.println("The strings are equal");
        }
     }
 }

在python中==是通过重写operator.eq(a, b)方法来比较对象的内容,strclass已经重写了这个顺序比较对象的内容

These are the so-called “rich comparison” methods. The correspondence 
between operator symbols and method names is as follows: x<y calls 
x.__lt__(y), x<=y calls x.__le__(y), x==y calls x.__eq__(y), x!=y calls 
x.__ne__(y), x>y calls x.__gt__(y), and x>=y calls x.__ge__(y).

但是在java中使用了==运算符来比较对象的引用here

Using the “==” operator for comparing text values is one of the most common mistakes Java beginners make. This is incorrect because “==” only checks the referential equality of two Strings, meaning if they reference the same object or not.

所以在 java 中比较你必须使用 equals 的对象的内容,它在 String class.

中被覆盖
if (str1.equals(str2))

so java == 运算符等于 python 中的 is 运算符比较两个引用是否指向同一对象

解释的很好here:

这是该网站的引述: "We can use == operators for reference comparison (address comparison) and .equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects."

Python 的 str class 对其 __eq__ 方法使用值相等。在 Python 中,classes 可以覆盖 __eq__ 来定义 == 的行为方式。

将其与 Java 进行对比,其中 == 始终执行引用相等。在 Java 中,== 只会 return true 如果两个对象实际上是同一个对象;不管他们的内容。 Java 的 == 与 Python 的 is 运算符更具可比性。

如评论中所述,更好的比较是比较这些:

"a".equals("a")  // Java

"a" == "a"  # Python

Java 的 String class 有其 equals 做值相等而不是引用相等。