-3

Im having some issues sorting a ArrayList that contains ArrayLists

ArrayList<ArrayList<String>> multiMarkArray = new ArrayList<ArrayList<String>>();

String line;
while ((line = bufRdr.readLine()) != null) {
    ArrayList<String> singleMarkArray = new ArrayList<String>();
    for (String word : line.split(" ")) {
        singleMarkArray.add(word);
    }
    Collections.swap(singleMarkArray, 0, 1);
    multiMarkArray.add(singleMarkArray);
}

Collections.sort(multiMarkArray);
System.out.println(multiMarkArray);

Im getting the error Collections cannot be applied to (java.util.ArrayList>)

Can someone point me in the right direction to solving this issue?

Thanks

venomphil
  • 39
  • 1
  • 8

4 Answers4

2

If you want to sort all lists contained in multiMarkArray you should do

for (ArrayList<String> strings : multiMarkArray) {
       Collections.sort(strings);
}

instead of

Collections.sort(multiMarkArray);

This will sort the Strings in each list. But the sortation of the lists in multiMarkArray won't be affected.

codinghaus
  • 2,218
  • 1
  • 14
  • 19
1

You can only sort Collections that contain elements that implement Comparable.

Dennishofken
  • 317
  • 2
  • 9
0

In order to sort, you need a sorting criterion. ArrayLists don't have a built-in sorting criterion because there's no natural way to compare two ArrayLists.

You have to provide a criterion by calling the version of sort with two arguments and passing a Comparator<ArrayList<String>>.

Marco
  • 479
  • 4
  • 10
0

Collections sort is applicable with "comparable" Object (extends Comparable):

public static <T extends Comparable<? super T>> void sort(List<T> list)
Sorts the specified list into ascending order, according to the natural ordering of its elements. 

or you can send sort method with second parameter with your own Comparator:

public static <T> void sort(List<T> list,
            Comparator<? super T> c)
Sorts the specified list according to the order induced by the specified comparator. 
Ori Marko
  • 56,308
  • 23
  • 131
  • 233