Home > Back-end >  When I compare Character in java, Why is equals() not working, but == is?
When I compare Character in java, Why is equals() not working, but == is?

Time:09-16

I'm trying to solve the classic Valid Parentheses question on LeetCode.

This is what I did, and it can pass all the test cases:

public boolean isValid(String s) {
    Deque<Character> stack = new LinkedList<>();
    for (Character c : s.toCharArray()) {
        if (c.equals('{') || c.equals('[') || c.equals('(')) {
            stack.push(c);
        } else {
            Character check = stack.isEmpty() ? ' ' : stack.pop();
            if (check != (c - 1) && check != (c - 2)) { //***
                return false;
            }
        }
    }
    return stack.isEmpty();
}

but when I change the line *** into this:

if (!check.equals(c - 1) && !check.equals(c - 2)) {}

Although it can pass the compiler, but it can not return the right answer, not even the simple input like "()".

Normally, shouldn't we are supposed to use equals() rather than == to compare Character?

CodePudding user response:

If you add debugging to the if block in question

System.out.println(c);
System.out.println(c -1);
System.out.println(c -2);

you will see the char followed by two int values.

In your original code, type casting was taking place.

In my IDE, there is even a warning

Unlikely argument type for equals(): int seems to be unrelated to Character

As summed up in the comments above:

subtracting an int from a Character will return an int value. You need to cast it back as char when using equals as it will be auto-boxed as an Integer

  • Related