Return to Video

Implementing Comparable - Intro to Java Programming

  • 0:00 - 0:04
    Because strings are comparable, we can sort them by writing one line of code.
  • 0:04 - 0:08
    If I create an array list of strings and add a whole bunch of things not in any
  • 0:08 - 0:11
    order, and then I want to print them out in alphabetical order, I can add the
  • 0:11 - 0:18
    line collections.sort strings. Collections is a class a little bit like a race
  • 0:18 - 0:23
    that has some useful utility methods. If I compile and run this code, it will
  • 0:23 - 0:29
    print out all of the animals that I added to the list, but from A to W. We
  • 0:29 - 0:32
    might want to be able to sort countries like this too. Let's say countries are
  • 0:32 - 0:36
    naturally ordered by their areas. Let's implement the compareTo method for
  • 0:36 - 0:40
    countries. I want to be able to make an array of countries like this, and then
  • 0:40 - 0:43
    use the sort method in the arrays class to sort all of the countries in the
  • 0:43 - 0:48
    array, so that this will work. Let's implement the comparable method for
  • 0:48 - 0:54
    countries. We'll need to make the country measurable and also comparable. Now
  • 0:54 - 0:58
    the method should be public and return an int. It's called compareTo, and it
  • 0:58 - 1:03
    takes an object, otherObject. Now if we want to compare otherObject to this
  • 1:03 - 1:06
    object, the first thing we'll need to do is check whether otherObject actually
  • 1:06 - 1:11
    has a name and an area. If otherObject is not a country, then it doesn't really
  • 1:11 - 1:15
    make sense to compare it to this country. If you keep studying Java, you'll
  • 1:15 - 1:19
    figure out how to avoid this cast using generics. For now though, let's focus
  • 1:19 - 1:23
    on the compareTo method. For now, fill in the code, so that compareTo works as
  • 1:23 - 1:28
    I described before for countries. Return a negative number if this country is
  • 1:28 - 1:32
    smaller than other, positive is this country is larger, zero if the two
  • 1:32 - 1:38
    countries are equal. And notice, I implemented .equals for you. So, you can use
  • 1:38 - 1:42
    this. And if the countries are exactly the same size, you can break ties using
  • 1:42 - 1:46
    the name. Can you fill in the rest for me?
Title:
Implementing Comparable - Intro to Java Programming
Description:

more » « less
Video Language:
English
Team:
Udacity
Project:
cs046: Intro to Programming
Duration:
01:47

English subtitles

Revisions Compare revisions