Skip to content
Advertisement

problem with equals() method when used after toString() method

When I tried to take two strings as input to a function and check whether they are anagrams, I am getting the wrong output. I have written the following code.

    class Solution {
    public boolean isAnagram(String s, String t) {
        char sArray[] = s.toCharArray();
        char tArray[] = t.toCharArray();
        Arrays.sort(sArray);
        Arrays.sort(tArray);
        s = sArray.toString();
        t = tArray.toString();
        return s.equals(t);
        
    }
}

The sample input I have taken is s = "anagram" and t = "nagaram" . When checked, both the char arrays are printing the same value, i.e.

sArray is: 
aaagmnr
tArray is: 
aaagmnr

But my output seems to be false. Could someone please help me why am I getting such result when I use equals() after toString()?

Advertisement

Answer

Your conversion to String is incorrect, since arrays don’t override the Object implementation of toString().

That said, there is no reason to convert the arrays to String in order to compare them. You can compare them directly using Arrays.equals which will return true if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal.

char sArray[] = s.toCharArray();
char tArray[] = t.toCharArray();
Arrays.sort(sArray);
Arrays.sort(tArray);
return Arrays.equals(sArray,tArray);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement