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"}

Respuesta :

Answer:

Use set function

temp=a.get(j)

a.set(j,a.get(j+1));

a.set(j+1,temp)

Explanation:

public static ArrayList<String> swapPairs(ArrayList<String> strings)

{

//if size is under 2 (0 or 1), there is nothing to swap, so return the original list

if (strings.size() < 2)

{

return strings;

}

//define new string list and counter

ArrayList<String> newStringList = new ArrayList<String>();

int count;  

//count by every two since we are swapping every two values...

for (count = 0; count < strings.size() - 1; count+=2)

{

newStringList.add(strings.get(count+1));

newStringList.add(strings.get(count));

}  

//if there is still one value left (the last value of an odd sized list), add it to the end of the new list

if (count < strings.size())

{

newStringList.add(strings.get(count));

}

return newStringList;

}

ACCESS MORE