BednarQ BednarQ - 22 days ago 5
Java Question

Sort alphabetically ArrayList of Strings in java

I am trying to sort an ArrayList of strings. So far I have tried using

ArrayList.sort
but I am note sure how to use it properly.

My class looks like this:

ArrayList<String> arraylist = new ArrayList<>();
String value,value1,value2;
value="String1";
value1="String2";
value3="String3";

arraylist.add(value);
arraylist.add(value1);
arraylist.add(value2);


I have no idea how to sort this one.
Last time when I was using ArrayList of custom objects like

ArrayList<myObject> = new ArrayList<>();


I implemented
Comparable
interface, then I overrode the
compareTo
method in myObject class and everything was...easier.

How do I sort with ArrayList using just simple Strings?

@Edit
Trying few things on my own, I've used
arraylist.sort(null)
and somehow it worked like it was supposed to. No more help is needed, thank you guys.

Answer

The sort() of ArrayList only works if you are proving a Comparator.

For the String Double Integer you can use Collection.sort(). It directly modifies the arraylist you pass instead of returning a new arraylist.

Code:

public static void main(String[] args) 
    {

        ArrayList<String> arraylist = new ArrayList<>();
        String value,value1,value2;
        value="C";
        value1="Z";
        value2="A";

        arraylist.add(value);
        arraylist.add(value1);
        arraylist.add(value2);
        System.out.println(arraylist);
        Collections.sort(arraylist);
        System.out.println(arraylist);
}