0

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

4
  • 4
    why not use Comparator? Commented Mar 29, 2013 at 5:21
  • What is the type of the truth values ? String ? How do you compare values in the compareTo ? Commented Mar 29, 2013 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 Commented Mar 29, 2013 at 5:28
  • 1
    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 Commented Mar 29, 2013 at 6:14

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.