0

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.

BednarQ
  • 139
  • 3
  • 15

1 Answers1

0

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);
}
SkrewEverything
  • 2,393
  • 1
  • 19
  • 50
  • Tried this one in a first place since ArrayList.sort didn't work for me and all I've got was "Method call expected" – BednarQ Nov 18 '16 at 18:10
  • @BednarQ It's working fine for me. Can you please provide your whole code with `Collections.sort()`? With your imports,class,main(). – SkrewEverything Nov 18 '16 at 18:12
  • I've tried `arrayList.sort(null)` and somehow it worked like it was expected to, so I think i dont need more help. Thank you anyway – BednarQ Nov 18 '16 at 18:18