3

I was trying to get the equality of 'ü' == 'ü'. This returns true if I write like this (in sout). But in my code:

static Character[] charset = {'ü'};

    public static void main(String[] args) {
        ArrayList<Character> mustContain = new ArrayList<>();
        mustContain.add('ü');
        ArrayList<Character> removal = new ArrayList<>();
        for (int i = 0; i < charset.length; i++) {
            for (int j = 0; j < mustContain.size(); j++) {
                if(charset[i] == 'ü' && mustContain.get(j) == 'ü') {
                    System.out.println(charset[i] instanceof Character);
                    System.out.println(mustContain.get(j) instanceof Character);
                }
                if(charset[i] == (mustContain.get(j))){
                    System.out.println("added");
                    removal.add(mustContain.get(j));
                }

            }
        }

        System.out.println(Arrays.toString(removal.toArray()));
    }

This is the result:

true
true
[]

What I hope to get was:

true
true
added
[ü]

I can only get this equality as true with charset[i].equals(mustContain.get(j))

But for the Character 'a' everything is okay with the code, both == and .equals() returns true. For 'ü' only .equals() works. I really wonder why equals works and == not?

Ahmet Aziz Beşli
  • 1,280
  • 3
  • 19
  • 38
  • 1
    I assume it's the same reason as [Weird Integer boxing in Java](https://stackoverflow.com/questions/3130311/weird-integer-boxing-in-java) – Jacob G. Nov 25 '19 at 03:45
  • That'd be my guess too. 'a' is a smallish integer (0x61), 'ü' is larger (0xfc),. –  Nov 25 '19 at 03:47
  • Yes, that's strange. Replacing ü with another char, for instances 'a', works as expected. Interesting... – Enrico Giurin Nov 25 '19 at 04:07

1 Answers1

2

My answer to this behavior is that == performs reference comparison.

Try to set up a break point at the line

if(charset[i] == (mustContain.get(j))

By inspecting charset[i] and mustContain.get(j) You will see that the reference is different for the case of the special character, which gives the result: false.

CK_D
  • 36
  • 4