简体   繁体   中英

Trying to compare two strings in Java using equals()

I have tried a number of ways to compare two strings of 'phone numbers' and none seem to pass the tests. the code I am currently using:

public boolean equals (PhoneNumber other) {     
    boolean results = other.equals(digits);
    return results;
}

The test I am trying to pass without hard coding for it:

p = new PhoneNumber("5551212");
    p2 = new PhoneNumber("5551212", "Home");
    displayResults(p.equals(p2));
    p.setDigits("1234123");
    displayResults(p.equals(p2) == false);

Two separate problems:

[1] digits is a string; other is a phonenumber. these will NEVER be equal. What you're presumably looking for, is other.digits.equals(this.digits) . Now we're comparing the digits of phone number A with the digits of phone number B: Apples and apples. That has a chance of working out.

[2] the equals method's signature is public boolean equals(Object other) . Your equals method has a different signature, which means, it is an entirely different method with no relation whatsoever to the real equals method.. other than the coincidence that it so happens to share a name with it. It means your 'fake' equals method would not be used by other code that uses equals methods. Such as the contains method of an arraylist, for example. The solution is to make that equals method have as argument Object other .

[3] when you do that, you won't be able to call .digits on other ; after all, only phonenumbers have digits; any random object isn't guaranteed to. The solution is to cast the other , but only do that after checking if it is a phonenumber:

public boolean equals(PhoneNumber other) {
    if (!(other instanceof PhoneNumber)) {
        // somebody is comparing apples to oranges. Obviously, then...
        return false;
    }
    return ((PhoneNumber) other).digits.equals(this.digits);
}

note also that for proper operation of such an object in, say, HashSet , you must always override both the hashCode and the equals method, or neither.

Project Lombok automates all this stuff, you may be interested in this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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