Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a generic method to exchange the positions of two different elements in an

ID: 3824814 • Letter: W

Question

Write a generic method to exchange the positions of two different elements in an array. Lets say the method name is "swap". It will take three parameters, a generic array called 'a', and two integer positions (i and j). For method swaps the element of 'a' i^th element of array 'a' with the j^th element. For example, I have provided some test calls of the swap method from the main that shows how this method could be called for two different types of array. Your program should work without changing anything in the main method. public class GenericAlgorithm {//define the public static void swap (generic) method here public static void main (String [] args) {Integer [] List = {1, 5, 4, 10};//call swap on an Integer array swap (iList, 1, 2); for (Integer i: iList) System.out.print (i +", ");//should print 1, 4, 5, 10, String [] sList = {"one", "five", "four", "ten"};//call swap on a string array swap (sList, 3, 2); for (String s: sList) System.out.print (s + ", ");//should print one, five, ten, four, }}

Explanation / Answer

Answer

Solution

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;


public class Main {
public static final <T> void swap (T[] iList, int i, int j) {
T t = iList[i];
iList[i] = iList[j];
iList[j] = t;
}

public static final <T> void swap (List<T> sList, int i, int j) {
Collections.<T>swap(sList, i, j);
}

private static void test() {
Integer [] iList = {1,5,4,10};
swap(iList, 1, 2);
System.out.println("a:"+Arrays.toString(iList));
  
String[] sList1 = {"one" , "Five" , "Four" ,"ten"};
List<String> sList = new ArrayList<String>(Arrays.asList(sList1));
swap(sList, 3, 2);
System.out.println("l:"+sList);
}
public static void main(String[] args)
{
test();
}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote