Java Java Data Structures Organizing Data Interfaces

sort() and compareTo()

Hello, I don't know what to import / implement to use the compareTo() method and the same goes for the sort() method. Can someone explain to me please? And does the compareTo() method work directly( without us having to implement/import anything) on Strings?

1 Answer

Juraj Sallai
Juraj Sallai
7,187 Points

You can use compareTo() for simply comparing two objects. In our case Treet objects, which we decided will be compared by creation date. Like this:

System.out.println(treet.compareTo(treet2));

Or if you add your object to Array, you can sort this Array of object by creation date (in our case). Hope it helps:

    Treet treet1 = new Treet(name1, description1, date1);
    Treet treet2 = new Treet(name2, description2, date2);

    Treet[] arrayOfTreets = new Treet[2];
    arrayOfTreets[0] = treet1;
    arrayOfTreets[1] = treet2;

   // This will sort our array by creation date -because sort method calls compareTo() method, which we have overriden.
    Arrays.sort(arrayOfTreets);