English sottotitoli

← Arrays or ArrayLists - Intro to Java Programming

Ottieni il codice di inserimento
5 Lingue

Mostrare Revisione 4 creata 05/24/2016 da Udacity Robot.

  1. So, we have arrays and we have arraylists, and it's
  2. a bit of a nuisance that we have both. Because it
  3. means that we have to make a decision between them
  4. whenever we want to collect elements. Generally, arraylists are more convenient
  5. because they can grow and shrink. But there are a
  6. few reasons why you might want to prefer arrays. First off, the
  7. syntax for the brackets, is more compact. For example here,
  8. we assign values one to values two and that's a bit
  9. easier to read than the equivalent with arraylists, which
  10. you see over here. Also, if you know exactly what
  11. values you want in a collection, then arrays give you
  12. an easier syntax. Here I have a string of workdays,
  13. and I know exactly that I want these five
  14. strings. No more, no less. I know what they are.
  15. Then I can use this handy syntax, to construct an
  16. array and initialize it right away. With an array list,
  17. I would have to call the add method five times,
  18. once for each of these strings. Another disadvantage of array lists
  19. is that they don't work well with numbers. We have
  20. never done that so far, but let's say we wanted to
  21. collect Numbers in an array list, I'd have to do
  22. something like this, and when you look carefully, you'll notice that
  23. the double here, has an uppercase D. Normally, when we
  24. want to have a floating point number, we write double with
  25. a lowercase d, and you may recall that the
  26. number types are not classes in Java. But inside, the
  27. angle brackets here, I must put in a class.
  28. An array list can only collect objects of a class.
  29. So for every number time, There is a companion
  30. class, called the wrapper class. And an object, of a
  31. wrapper, just has some number inside. If you have
  32. lots of numbers, say for the sake of the argument
  33. you have, 1,000,000 values, it takes a lot more
  34. space to store 1,000,000 wrappers each of which contains
  35. a number, than it would be to use an
  36. array That's contains the numbers directly. Most of the
  37. time, we're not that concerned about efficiency, but when
  38. you are, and need to collect a lot of
  39. numbers, definitely use an array. In conclusion, use an
  40. array list as a rule of thumb, unless you want
  41. the nice syntax that an array gives you. You having the brackets, having the
  42. initializers. Or you collect lots of numbers.
  43. In that case, array lists are quite inefficient.