简体   繁体   English

了解==和等于

[英]Understanding == and equals

I learned that == checks if the references being compared are the same,, while .equals() compares the two states. 我了解到==检查要比较的引用是否相同,而.equals()比较两个状态。 So then why can we use == inside the .equals() method? 那么,为什么我们可以在.equals()方法中使用==呢?

Like for example: 例如:

public boolean equals(Object o){
        //cast o to SimpleBankAccount
        SimpleBankAccount b = (SimpleBankAccount)o;

        //check if all attributes are the same
        if ((this.balance == b.balance) && (this.accountNumber == b.accountNumber)){
            return true;
        }
        else{
            return false;
        }
    }

Why would the this.balance and b.balance have the same reference? 为什么this.balance和b.balance具有相同的引用?

The equals method is to compare objects. equals方法是比较对象。 When using the "==" to test for equality, the only time it will function as expected is when it is comparing primitive or native types, or you are actually testing to see if two pointers refer to the same object. 当使用“ ==”进行相等性测试时,它唯一可以正常工作的是比较原始类型或本机类型时,或者您实际上正在测试以查看两个指针是否指向同一个对象。 That is, balance is more than likely of type int , float or double , which means "==" will test for equality as expected. 也就是说, balance很有可能是intfloatdouble类型的,这意味着“ ==”将按预期测试相等性。 If balance was of type Balance , then this would not work. 如果balance的类型为Balance ,那么它将不起作用。

引用也与基本类型以及int,char和double相似,因为在执行==时,您实际上是在比较这些类型的二进制表示形式。

because balance is likely a primitive, correct? 因为平衡可能是原始的,对吗? like an int or a float? 像是整数还是浮点数? so you are comparing the value of balance. 所以您正在比较余额的价值。 With objects you are comparing the references, but with primitives you are comparing the actual data value 使用对象时,您正在比较引用,但是使用基元时,您正在比较实际数据值

如果此equals方法有效,那是因为balanceaccountNumber变量是原始类型,例如intdouble ,并且==会比较原始类型的值。

Depends on what balance is. 取决于什么是平衡。

If balance is a primitive, then == will compare the values, which is correct. 如果balance是原始值,则==将比较这些值,这是正确的。

== is normally used inside the equals method to check if the two references are actually the same object. 通常在equals方法内使用==来检查两个引用是否实际上是同一对象。 If they are not, further checking goes to see if objects have the same state. 如果不是,则进一步检查以查看对象是否具有相同的状态。

If you want to compare the value of balance/accountNumber and they are primitives or primitive Wrappers (like Integer) then == is how you compare the value. 如果要比较balance / accountNumber的值,并且它们是原始值或原始包装程序(例如Integer),则==是比较值的方式。 The wrappers will be autoboxed. 包装器将自动装箱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM