Generic Sorting with Bounded Type Parameters
Here is the int-based ArrayUtils, working on the non-generic DynamicArray:
public static void swap(DynamicArray a, int i, int j) {
int temp = a.get(i);
a.set(i, a.get(j));
a.set(j, temp);
}
public static int indexOfMin(DynamicArray a, int from) {
int minIndex = from;
for (int i = from + 1; i < a.size(); i++) {
if (a.get(i) < a.get(minIndex)) {
minIndex = i;
}
}
return minIndex;
}
ArrayUtils is not a generic class; it is a namespace of static methods.
Solution
public static <T> void swap(DynamicArray<T> a, int i, int j) {
T temp = a.get(i);
a.set(i, a.get(j));
a.set(j, temp);
}
Since ArrayUtils has no class-level T, the static method declares its own type parameter, <T>, before the return type. swap never compares its elements, so no restriction on T is needed.
Solution
indexOfMin compares elements, so it needs to call compareTo on T, which means T must implement Comparable<T>. The type parameter is bounded: <T extends Comparable<T>>.
public static <T extends Comparable<T>> int indexOfMin(DynamicArray<T> a, int from) {
int minIndex = from;
for (int i = from + 1; i < a.size(); i++) {
if (a.get(i).compareTo(a.get(minIndex)) < 0) {
minIndex = i;
}
}
return minIndex;
}
swap is left unbounded because its body never needs compareTo. Bounding it anyway would only stop a caller from swapping elements of a type that is not Comparable, and that buys nothing. The rule is to add a bound only when the method body requires it.