English subtitles

← Friends Done Right - Intro to Java Programming

Get Embed Code
5 Languages

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

  1. Now that you know a little bit about ArrayLists, it's time to revisit an old
  2. friend, the Person class. I removed some of the methods and added one new one.
  3. GetFriend gets the ith friend, but as you can see it's a pretty ugly method.
  4. This is bad code. I wasn't careful when I wrote it and it's messy. It would
  5. work alright if my friends are named Madonna, Sting, and Cher. But most people
  6. have spaces in their names. Maybe I could fix this by separating the names with
  7. commas or semicolons. I could change the separator here. But that won't really
  8. fix the underlying problem. The underlying problem is that reality has
  9. structure and we need to choose the right data types to model that structure.
  10. In our case we have multiple individual people. A string of names isn't the
  11. right way to save a bunch of individuals who all play a similar role. An
  12. ArrayList would be much better for this. Saving an ArrayList of Person objects,
  13. instead of just a string of friends would allow us to do a lot of cool things.
  14. For example, we could add a string nationality to each person. And then you can
  15. get a list of all the countries your friends are from. But let's work our way
  16. up to problems like that. First, let's store the friends in an ArrayList of
  17. strings without changing the observable behavior. In software engineering this
  18. would be called refactoring. Refactoring is when you reorganize code. The
  19. implementation changes. The observable behavior does not change. Often we do
  20. this to make it easier to add new features. Now I want you to refactor the
  21. person class. I'll give you some tests so you can make sure nothing breaks in
  22. the process. You'll need to update the instance variables. Save the friend's
  23. names in an ArrayList of strings. You'll need to update addFriend, getFriend
  24. and getFriends. We'll skip unfriend for the moment, but we will come back to it
  25. later. And I'm going to give you a hint. Do you remember the toString method
  26. from lesson two? ToString returns a representation of the object, and works
  27. pretty well for ArrayList of strings. Let me show you what it does. If I create
  28. an ArrayList, strs, and add a couple of strings to it, like this, and then I
  29. call the toString method. The toString method returns, a string, that has the
  30. values separated by commas and spaces and then surrounded by brackets. This is
  31. pretty close to what you want for the getFriends method. For the getFriends
  32. method, you just want the values separated by commas and spaces. And here's one
  33. last hint. If you get an error that Java doesn't know what an ArrayList is, you
  34. might need to import it.