Ask Question
2 May, 15:56

Write a method swapPairs that switches the order of values in an ArrayList of Strings in a pairwise fashion. Your method should switch the order of the first two values, then switch the order of the next two, switch the order of the next two, and so on. For example, if the list initially stores these values: {"four", "score", "and", "seven", "years", "ago"} your method should switch the first pair, "four", "score", the second pair, "and", "seven", and the third pair, "years", "ago", to yield this list: {"score", "four", "seven", "and", "ago", "years"} If there are an odd number of values in the list, the final element is not moved. For example, if the original list had been: {"to", "be", "or", "not", "to", "be", "hamlet"} It would again switch pairs of values, but the final value, "hamlet" would not be moved, yielding this list: {"be", "to", "not", "or", "be", "to", "hamlet"}

+5
Answers (1)
  1. 2 May, 18:50
    0
    public static void swapPairs (ArrayList strList)

    {

    for (int i = 0; i < strList. size () - 1; i + = 2)

    {

    String temp1 = strList. get (i);

    String temp2 = strList. get (i + 1);

    strList. set (i, temp2);

    strList. set (i + 1, temp1);

    }

    }
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “Write a method swapPairs that switches the order of values in an ArrayList of Strings in a pairwise fashion. Your method should switch the ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers