So I have this method which will take an ArrayList of Integers, I compare between 2 sub arrays and preform some swapping of numbers.
I am comparing the first elements of each sub array which is just the array halved, then swapping the elements if the bigger number isn’t in the left subList. after that I want to recursively do the same thing but to the first half.
so if I type 3 5 8 2 1 7 6 4
I want to see this;
[3, 5, 8, 2, 1, 7, 6, 4]
[3, 7, 8, 4, 1, 5, 6, 2]
[8, 7, 3, 4, 1, 5, 6, 2]
[8, 7, 3, 4, 1, 5, 6, 2]
What I want to be able to do is once I have done what I need to, to the base array, I need to work on the first half of the same array recursively. However when I compile, I get an error saying that I have incompatible types. So I’m assuming the subList function isn’t providing me a ArrayList.
Any pointers on gettign this to work correctly?
public static void tournament(ArrayList<Integer> players){
int mid = players.size()/2;
for(int i=0; i < mid; i++){
if(players.subList(0,mid).get(i) < players.subList(mid,players.size()).get(i)){
int temp = players.subList(0,mid).get(i);
players.subList(0,mid).set(i , players.subList(mid,players.size()).get(i));
players.subList(mid,players.size()).set(i,temp);
}// end if
}// end for
System.out.println(players);
if(players.size() > 2){
tournament(players);
}// end if
}// end tournament
With the Collections API (of which the
ArrayListis part), the best-practice is to declare your variables using the generic interfaces:List,Set,Map, rather than their concrete implementations such asArrayList,HashSetandHashMap.For example, instead of this:
you should do this:
If you take a look at the JavaDoc for java.util.List.subList(), you’ll see that the method signature is this:
ArrayList, as an implementation of theListinterface, uses this exact same signature. Note that the return type isList, and notArrayList. What this means is thatArrayList.subList()doesn’t have to return you anArrayList(although it could) – it simply has to return you an object that conforms to theListinterface.So what is the first step? Change your method to accept a
Listrather than anArrayList. (Whatever method calls yourtournament()initially method can still pass anArrayList.)