Java Guild Meeting 5/2018

Gi11i4m
2,072 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content
Previous: Generics Next: Thanks for playing!

Generifying existing code.

For the second exercise, you start with a method that does not yet use generics. The method returns a copy of an array with two elements swapped.

There are a few directions in which you could take this method. Try out the following exercises. Don't forget to write tests! You can reuse the class hierarchy from the previous exercise to write tests and experiment. As a reminder again: don't forget that e.g. List<String> is not a subclass of List<Object>, but String[] does inherit from Object[]!.

  1. The method for swapping elements in an array does not use generics, please change the method so it returns an array of the same type as provided. Hint: look at Arrays::copyOf
  2. Write a method that does the same thing, but for lists.
  3. As an extra, allow the results from (1) and (2) to return an array/list of a supertype of the type in the original array/list, e.g. supply a Integer[] and allow the result of the method to be assigned to a Number[].
Generify the implementation
1
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// {...}
import java.util.ArrayList;
import java.util.List;
public class SwapUtil {
public static Object[] swapElements(Object[] array, int firstIndex, int secondIndex) {
Object[] copyOfArray = new Object[array.length];
System.arraycopy(array, 0, copyOfArray, 0, array.length);
copyOfArray[firstIndex] = array[secondIndex];
copyOfArray[secondIndex] = array[firstIndex];
return copyOfArray;
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content