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");
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");
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
)