Sim
Sim

Reputation: 590

Trying to sort an ArrayList of Arraylists

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?

Cheers,

Sim

Upvotes: 0

Views: 639

Answers (1)

Bernd Ebertz
Bernd Ebertz

Reputation: 1327

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>>() {
    @Override
    public int compare(List<Comparable> o1, List<Comparable> o2) {
      return o1.get(0).compareTo(o2.get(0));
    }
  };
  Collections.sort(knowledgeD, order);

Upvotes: 1

Related Questions