-2

So I need to sort an arraylist only using .compareTo any help here is my arraylist Thanks

ArrayList<String> Lists = new ArrayList<>();
        Lists.add("Rabbit");
        Lists.add("Fish");
        Lists.add("Dog");
        Lists.add("Cat");
BH_135
  • 11
  • 2
  • You should probably look at [how to ask a good question](http://stackoverflow.com/help/how-to-ask). – John Apr 24 '15 at 02:25
  • I tried a few stuff but since I can only use .compareTo it is hard to find material because a lot of them are using two arraylist not just one – BH_135 Apr 24 '15 at 02:26
  • 1
    ok, some other keywords that might help: ' Collections', 'Bubblesort', 'Quicksort'. But still, pls do some research before asking, this isn't that hard, even for a complete beginner –  Apr 24 '15 at 02:31
  • Did you want case sensitive or case in sensitive sort ? – user3145373 ツ Apr 24 '15 at 02:47
  • String is comparable. Compare one string to another. – D. Ben Knoble Apr 24 '15 at 02:51
  • @BH_135 Is this for an assignment? If so, please clarify if you _need_ to implement your own sort algorithm using compareTo, or if you just want to sort this ArrayList any old way – Drakes Apr 24 '15 at 03:40

1 Answers1

0

Using Collections.sort(Lists) will solve your problem much faster. Here is some sample code:

ArrayList<String> list = new ArrayList<>();
        Lists.add("Rabbit");
        Lists.add("Fish");
        Lists.add("Dog");
        Lists.add("Cat");

Collections.sort(list);
System.out.println(list); // this will print an alphabetically sorted list.

The technical details:

The sort function uses the compareTo() of each element in the list as it sorts it. So if you want to create some sort of custom sorting, then you don't actually modify the List itself, but rather override the compareTo() of the elements in the list (in this case String)

jeanluc
  • 1,608
  • 1
  • 14
  • 28