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?
Juraj Sallai7,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:
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; arrayOfTreets = treet1; arrayOfTreets = treet2; // This will sort our array by creation date -because sort method calls compareTo() method, which we have overriden. Arrays.sort(arrayOfTreets);