user2533660 user2533660 - 29 days ago 8
Java Question

Java Collections.sort not sorting arraylist.

So I have a program that is supposed to take 2 lines of input from system.in and check if they are anagrams (consisting of the same characters). It takes the strings from the two lines, puts each letter of the strings into separate arraylists, sorts them alphabetically, and returns true or false depending on if the arraylists are equal to each other.

static boolean isAnagram(String a, String b){
ArrayList<String> arrayA = new ArrayList<String>();
ArrayList<String> arrayB = new ArrayList<String>();

String tempSubstring;

for(int i = 0; i < a.length()-1; i++){
tempSubstring = a.substring(i,i+1).toLowerCase();
arrayA.add(tempSubstring);
}

for(int i = 0; i < b.length()-1; i++){
tempSubstring = b.substring(i,i+1).toLowerCase();
arrayB.add(tempSubstring);
}

Collections.sort(arrayA);
Collections.sort(arrayB);

if(arrayA.equals(arrayB)){
return true;
}else{
return false;
}
}


If I input "anagram" and "margana" it should return true, but it returns false because the
Collections.sort()
does not actually sort the arraylist. Instead, the arraylists are left as:

[a, n, a, g, r, a]
[m, a, r, g, a, n]


Any ideas as to why?

Answer

Collections.sort() is not the problem, it does sort the lists alphabetically. The problem is you are not building the lists from the strings correctly, you're not including the last letter of each String, hence the disparity when comparing both.

The for loops' stop conditions should be i < a.length() and i < b.length(), rather.

Anyway, here is a better version of your code that avoids the following bad practices:

  • Declaring a variable of type ArrayList (an interface implementation) rather than the interface it implements, List.
  • Using a built-in way to build Lists from arrays: Arrays.asList().
  • Returning the boolean evaluation that has already been made rather than been redundant.

Here it is:

static boolean isAnagram(String a, String b) {
    List<String> aList = new ArrayList<>(Arrays.asList(a.split("")));
    List<String> bList = new ArrayList<>(Arrays.asList(b.split("")));

    Collections.sort(aList);
    Collections.sort(bList);

    return aList.equals(bList);
}