English subtitles

← Implementing Comparable - Intro to Java Programming

Get Embed Code
6 Languages

Showing Revision 4 created 05/25/2016 by Udacity Robot.

  1. Because strings are comparable, we can sort them by writing one line of code.
  2. If I create an array list of strings and add a whole bunch of things not in any
  3. order, and then I want to print them out in alphabetical order, I can add the
  4. line collections.sort strings. Collections is a class a little bit like a race
  5. that has some useful utility methods. If I compile and run this code, it will
  6. print out all of the animals that I added to the list, but from A to W. We
  7. might want to be able to sort countries like this too. Let's say countries are
  8. naturally ordered by their areas. Let's implement the compareTo method for
  9. countries. I want to be able to make an array of countries like this, and then
  10. use the sort method in the arrays class to sort all of the countries in the
  11. array, so that this will work. Let's implement the comparable method for
  12. countries. We'll need to make the country measurable and also comparable. Now
  13. the method should be public and return an int. It's called compareTo, and it
  14. takes an object, otherObject. Now if we want to compare otherObject to this
  15. object, the first thing we'll need to do is check whether otherObject actually
  16. has a name and an area. If otherObject is not a country, then it doesn't really
  17. make sense to compare it to this country. If you keep studying Java, you'll
  18. figure out how to avoid this cast using generics. For now though, let's focus
  19. on the compareTo method. For now, fill in the code, so that compareTo works as
  20. I described before for countries. Return a negative number if this country is
  21. smaller than other, positive is this country is larger, zero if the two
  22. countries are equal. And notice, I implemented .equals for you. So, you can use
  23. this. And if the countries are exactly the same size, you can break ties using
  24. the name. Can you fill in the rest for me?