switchPairs
Category: ArrayList
Author: Stuart Reges
Book Chapter: 10.1
Problem: switchPairs
Write a static method switchPairs 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")
You may assume that the ArrayList you are passed contains only Strings.
Recall that the primary methods for manipulating an ArrayList are:
add(E value) appends value at end of list
add(int index, E value) inserts given value at given index, shifting
subsequent values right
clear() removes all elements of the list
get(int index) returns the value at given index
remove(int index) removes and returns value at given index,
shifting subsequent values left
set(int index, E value) replaces value at given index with given value
size() returns the number of elements in list
Write your solution to switchPairs below.