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

Java Programming 1) Generics and Wildcards 1.Write a static generic method calle

ID: 3710784 • Letter: J

Question

Java Programming

1) Generics and Wildcards

1.Write a static generic method called swapPlaces that swaps the position of two elements in an array. This method should take in an array of a generic type (Object and all subclasses) and two int values to represent the array positions to swap (no need to perform error checking – although in a real application, you definitely should!)

2.Create a method that overloads the method created in (1.1). This overloaded method should take an array of Number (and any subclasses).

3.Create a method that overloads the method created in (1.1). This overloaded method should take an array of Integer (and any subclasses)

Explanation / Answer

class Solution

{

    // generic method

    public static <E> void swapPlaces(E[] arr, int i, int j)

    {

        // swap elements at position i and j

        E temp = arr[i];

        arr[i] = arr[j];

        arr[j] = temp;

    }

   

    // overloaded Number class method

    public static void swapPlaces(Number[] arr, int i, int j)

    {

        // swap elements at position i and j

        Number temp = arr[i];

        arr[i] = arr[j];

        arr[j] = temp;

    }

   

    // overloaded integer method

    public static void swapPlaces(int[] arr, int i, int j)

    {

        // swap elements at position i and j

        Integer temp = arr[i];

        arr[i] = arr[j];

        arr[j] = temp;

    }

   

    public static void main(String[] args)

    {

        int i;

       

        int[] arr = { 0 , 1 , 2 , 3 , 4 , 5 };

       

        System.out.print("arr1 : ");

       

        for( i = 0 ; i < arr.length ; i++ )

            System.out.print(arr[i] + " ");

       

        System.out.println();

       

        swapPlaces( arr, 2 , 5 );

       

        System.out.print(" arr1 after swapping places at 2 and 5 : ");

       

        for( i = 0 ; i < arr.length ; i++ )

            System.out.print(arr[i] + " ");

       

        System.out.println();

    }

}

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