I am attempting to use generics that will sort an ArrayList in ascending order as extra practice for my upcoming mid-term exam. I am given the main method body, and the method header for the sorting method, and am asked to write the method body for the sort method. However, I am getting errors on a couple of lines(which I will denote with an asterisk and question mark). Where am I going wrong(I used a similar program in attempting to help me build the method body):
import java.util.ArrayList; //imports ArrayList class for method usage
public class ProblemTwo {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>(); //creates an ArrayList that can only contain Integer type values
list.add(14);
list.add(24);
list.add(4);
list.add(42);
list.add(5);
ProblemTwo.<Integer>sort(list); //calls the sort method to sort only Integer types
System.out.print(list);
}
public static <E extends Comparable<E>> void sort(ArrayList<E> list) { //invokes sort method, passing concrete generic types from main method to formal generic types
E currentMinValue; //creates current minimum value based on generic type
int currentMinIndex; //used to set index for current minimum value
for (int i = 0; i < list.size()-1; i++){ //uses a loop to assign currentMinValue and currentMinIndex
currentMinValue = list.get(i); //assigns value at i to currentMinValue
currentMinIndex = i; // assigns current i as minimum index
for (int j = i + 1; j < list.size(); j++) { //uses a new loop to swap values if list(j) is less than list(i)
*? if (currentMinValue.compareTo(list.get(j))) {
currentMinValue = list.get(j);
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
*? list.get(currentMinIndex) = list.get(i);
*? list.get(i) = currentMinValue;
}
}
}
}