Take the 2-minute tour ×

trying to sort an Arraylist I have that contains the following

[[2/11, 11/48], [8/35, 35/288], [16/43, 43/288], [4/5, 5/16], [75/152, 19/210], [135/163, 163/1680]]

Currently I have sorted this Arraylist using,

for(int j = 0; j < knowledgeD.size()-1; j++) {

            if(knowledgeD.get(j).get(0).compareTo(knowledgeD.get(j+1).get(0)) == 1) {
                Collections.swap(knowledgeD, j, j+1);   

This orders the truth values, which are the first values in each brackets so, 2/11 8/35 etc etc it orders them in terms of value, so smallest to largest,

However, I notice that it messed up in the middle somewhere and hasn't ordered the 4/5 and 75/132, and I cannot work out why. I tried to add this fail safe code to do the obvious,

for(int k = 0; k < knowledgeD.size()-3; k++) {
                    if(knowledgeD.get(k).get(1).compareTo(knowledgeD.get(k+1).get(1)) == -1){
                        Collections.swap(knowledgeD, k-1, k+1);

however I keep getting index out of bounds errors now that I have this code implemented. Can anyone lend a hand?



share|improve this question
why not use Comparator? –  OQJF Mar 29 '13 at 5:21
What is the type of the truth values ? String ? How do you compare values in the compareTo ? –  James Poulson Mar 29 '13 at 5:24
I can't add a extra methods, so Comparator can't be used, the compareTo compares BigFractions which is a data type defined in another class which lets me used the method compareTo ( Bigfraction f) etc –  Sim Mar 29 '13 at 5:28
At least in your last loop you need to replace Collections.swap(knowledgeD, k-1, k+1); with Collections.swap(knowledgeD, k, k+1);. When k=0, you are trying to fetch value at index -1 if the condition matches –  BGR Mar 29 '13 at 6:14
add comment

1 Answer

As far as I understand it you try to order a list based on the natural order of the first element of child lists. In java this is typically done by an comparator and there is no need to add a new method to anything:

  Comparator<List<Comparable>> order = new Comparator<List<Comparable>>() {
    public int compare(List<Comparable> o1, List<Comparable> o2) {
      return o1.get(0).compareTo(o2.get(0));
  Collections.sort(knowledgeD, order);
share|improve this answer
add comment

Your Answer


