Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialTomás Borges
4,394 Pointssort() 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
7,188 PointsYou 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);