Write a method switchPairs that switches the order of values in an ArrayList of
ID: 3783644 • Letter: W
Question
Write a 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" and "score", the second pair, "and" 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, the final element is not moved. For example, if the 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"]
Explanation / Answer
Hi Please find my code.
Please let me know in case of any issue.
import java.util.ArrayList;
import java.util.Arrays;
public class SwitchPair {
public static void switchPairs(ArrayList<String> list){
System.out.println(list);
// base case
if(list == null || list.size() <= 1)
return;
for(int i=0; (i+1)<list.size(); i= i+2){
String temp = list.get(i);
list.set(i, list.get(i+1));
list.set(i+1, temp);
}
System.out.println(list);
}
public static void main(String[] args) {
String[] arr1 = {"score", "four", "seven", "and", "ago", "years"};
ArrayList<String> list = new ArrayList<>(Arrays.asList(arr1));
switchPairs(list);
String[] arr2 = {"to", "be", "or", "not", "to", "be", "hamlet"};
list = new ArrayList<>(Arrays.asList(arr2));
System.out.println();
switchPairs(list);
}
}
/*
Sample run:
[score, four, seven, and, ago, years]
[four, score, and, seven, years, ago]
[to, be, or, not, to, be, hamlet]
[be, to, not, or, be, to, hamlet]
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.