This code is meant to compare the characters in two strings and see if they are the same. It does so by taking the strings, converting them to a char array, sorting them, and then comparing them.
private boolean sameChars(String firstStr, String secondStr)
{
return Arrays.equals(Arrays.sort(firstStr.toCharArray()), Arrays.sort(secondStr.toCharArray()));
}
When I compile this code, it highlights (firstStr.toCharArray())
and says 'void' type not allowed here
. What's causing the error and how would I fix it?
Arrays.sort()
doesn't return the array. You'll need to store the character array strings to local variables, then call sort on each variable, and then finally compare the two arrays using Arrays.equals()
:
char[] firstStrArr = firstStr.toCharArray()
char[] secondStrArr = secondStr.toCharArray()
Arrays.sort(firstStrArr);
Arrays.sort(secondStrArr);
return Arrays.equals(firstStrArr,secondStrArr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With