Why is this reversed StringBuilder not equal to the original String, when it is a palindrome?

Why So Serious :

I was trying to check that a String is a palindrome using StringBuilder and reverse(). For a word with no symmetry like "chan" it correctly returns false, but it also returns false for genuine palindromes like "madam".

Code:

StringBuilder str = new StringBuilder("madam");
StringBuilder str2 = new StringBuilder(str);
boolean res = str2.equals(str.reverse().toString().trim());
System.out.println(str + " " + str2);
System.out.println(res);

Output:

madam madam
false

I am running Eclipse Neon with Java 8.

Eran :

str.reverse().toString().trim() is a String, so it cannot be equal to a StringBuilder.

Try to compare 2 Strings instead:

boolean res=str2.toString().equals(str.reverse().toString().trim());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=138976&siteId=1