120k views
1 vote
Write a method called 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, then the next two, and so on. If the number of values in the list is odd, the method should not move the final element. For example, if the list initially stores ["to", "be", "or", "not", "to", "be", "hamlet"], your method should change the list's contents to ["be", "to", "not", "or", "be", "to", "hamlet"].

1 Answer

6 votes

Answer:

  1. import java.util.ArrayList;
  2. public class Main {
  3. public static void main(String[] args) {
  4. ArrayList<String> strList =new ArrayList<String>();
  5. strList.add("to");
  6. strList.add("be");
  7. strList.add("or");
  8. strList.add("not");
  9. strList.add("to");
  10. strList.add("be");
  11. strList.add("hamlet");
  12. swapPairs(strList);
  13. System.out.println(strList);
  14. }
  15. public static void swapPairs(ArrayList<String> list){
  16. for(int i=0; i < list.size()-1; i+=2){
  17. String temp = list.get(i);
  18. list.set(i, list.get(i+1));
  19. list.set(i+1, temp);
  20. }
  21. }
  22. }

Step-by-step explanation:

Firstly, let's create a method swapPairs that take one ArrayList (Line 18). In the method, use a for-loop to traverse through each item in the ArrayList and swap the items between the current items at index-i and at index-i+1 (Line 19-22). The index-i is incremented by two in next loop and therefore the next swapping will proceed with third and fourth items and so forth.

In the main program, create a sample ArrayList (Line 5-12) and then test the method (Line 14) and print the output (Line 15). We shall get [be, to, not, or, be, to, hamlet].

User Don Miguel
by
4.6k points