1

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()?

5 Answers5

4

The below line of code does not convert the char array to String:

s = sArray.toString();
t = tArray.toString();

This only converts the address into String, in order to convert the Array to String you should use: Arrays.toString(arrName)

Now the code will look like this:

public static boolean isAnagram(String s, String t) {
    char sArray[] = s.toCharArray();
    char tArray[] = t.toCharArray();
    Arrays.sort(sArray);
    Arrays.sort(tArray);
    s = Arrays.toString(sArray);
    t = Arrays.toString(tArray);
    return s.equals(t);  
}
  • 1
    Arrays.toString will return _[a, a, a, g, m, n, r]_ not _aaagmnr_ actually – Eklavya Oct 11 '20 at 06:27
  • 1
    Yes, it will return [a, a, a, g, m, n, r] but in case of comparing anagrams it won't effect the logic. – Prateek Srivastava Oct 11 '20 at 06:31
  • _in order to convert the Array to String_ this denotes something else actually, doesn't mean string representation of char array with _[_ and separated with ,(comma) – Eklavya Oct 11 '20 at 06:43
  • 1
    Still, you can simply use `new String(array)`, to get a plain representation, without additional commas or brackets. Further, the inherited `toString()` method of array produces a class name, followed by @ and the objects *hash code*. This has nothing to do with addresses. – Holger Oct 12 '20 at 13:21
2

Here, toString() on char array called toString() method herited from the object class which is :

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

So, use String.valueOf to convert a character array to String again

s = String.valueOf(sArray);
t = String.valueOf(tArray);

Since you need to just compare, you can directly compare the character array using Arrays.equals()

return Arrays.equals(sArray,tArray);
Eklavya
  • 17,618
  • 4
  • 28
  • 57
1

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);
Eran
  • 387,369
  • 54
  • 702
  • 768
1

You are comparing the memory address of the sArray and tArray in

    s = sArray.toString();
    t = tArray.toString();

I suggest that you loop through the value in the array and store it in the String.

    for( int i = 0; i < sArray.length; i++ )
        str += sArray[i];

    for( int i = 0; i < tArray.length; i++ )
        str2 += tArray[i];

Then do comparison like this:

return str.equals(str2);
Calmen Chia
  • 325
  • 1
  • 8
1

You can use public String(char[] value) to create a String out of the char[] e.g.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        System.out.println(isAnagram("anagram", "nagaram"));
    }

    public static boolean isAnagram(String s, String t) {
        char sArray[] = s.toCharArray();
        char tArray[] = t.toCharArray();
        Arrays.sort(sArray);
        Arrays.sort(tArray);
        s = new String(sArray);// Create String out of sArray
        t = new String(tArray);// Create String out of tArray
        return s.equals(t);
    }
}

Output:

true

Alternatively, you can use String#valueOf to create a String out of the char[]. There are many more solutions (e.g. comparing the char arrays directly using Arrays#equals, comparing each element of one array with those of the other etc.) and I would recommend you try as many as you can for learning purpose.

What went wrong with your approach?

sArray.toString() and tArray.toString() return different strings which you could have found out by printing them or by debugging your code. The reason behind this difference is the difference in the hash code of sArray and tArray. Check What is a debugger and how can it help me diagnose problems? to learn how to use a debugger to avoid such situations.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110