?

AP® Computer Science A

Free Version

Upgrade subject to access all content

Moderate

Sorting Letters in an ArrayList of Strings

APCSA-VKKPIE

Consider the following methods that accept a String as their parameter.

Note that Collections.sort(arraylist) will sort the array list in ascending order.

public static String sortStringA(String s)
{
    ArrayList<String> letters = new ArrayList<String>();
    for (int i=0; i<s.length(); i++)
    {
        letters.add(s.substring(i,i+1));
    }
    Collection.sort(letters);
    String newString="";
    for (String e : letters)
    {
        newString = newString + e;
    }
    return newString;
}
public static String  sortStringB (String s)
{
    ArrayList<String> letters = new ArrayList<String>();
    for (int i=0; i<s.length(); i++)
    {    
        letters.add(s.substring(i,i+1));
    }
    Collections.sort(letters);
    String newString="";
    for (String e : letters)
    { 
        newString = e + newString;
    }
    return newString;
}
public static String sortStringC(String s)
{
    ArrayList<String> letters = new ArrayList<String>();
    for (int i=0; i<s.length(); i++)
    {
        letters.add(s.substring(i,i+1));
    }
    Collections.sort(letters);
    String newString="";
    for (int i=letters.size()-1; i>=0; i--)
    {
        newString+=letters.get(i);
    }
    return newString;
}

What is the output from the following segment of code?

System.out.println(sortStringA("danger"));
System.out.println(sortStringB("danger"));
System.out.println(sortStringC("danger"));
A
adegnr
rngeda
adegnr
B
rngeda
rngeda
adegnr
C
adegnr
rngeda
regnad
D
adegnr
rngeda
rngeda
E
danger
regnad
regnad