Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Void type not allowed here when using toCharArray?

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?

like image 203
Bhaxy Avatar asked Sep 08 '25 14:09

Bhaxy


1 Answers

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);
like image 110
Kevin K Avatar answered Sep 10 '25 05:09

Kevin K