How to sort LinkedList <String>?
I need to sort LinkedList strings by the length of the strings, but I would like to keep the order of the strings of the same length (not sorted lexicographically).
Input Example:
this
is
just
a
test
Output Example:
a
is
this
just
test
I try to do this with the method Comparable<LinkedList<String>>and compareTo, but I do not get the correct output (mine still sorts it lexicographically)
public class Q3_sorting implements Comparable<LinkedList<String>> {
Scanner keyboardScanner = null;
LinkedList<String> fileList = new LinkedList<String>();
// [...] code here
public int compareTo(LinkedList<String> o) {
// TODO Auto-generated method stub
o = fileList;
for (int i = 0; i < fileList.size() -1; i++) {
if (fileList.get(i).length() == o.get(i+1).length()) {
return 0;
}
if (fileList.get(i).length() > o.get(i+1).length()) {
return -1;
}
if (fileList.get(i).length() < o.get(i+1).length()) {
return 1;
}
}
Then I use
Q3_sorting sort = new Q3_sorting(args);Collections.sort(sort.fileList);
in my main method. Then I print the list ...
but I get this as output:
a
is
just
test
this
How can I fix this problem?
+5
4 answers