Collection Interface vs arrays

后端 未结 5 505
庸人自扰
庸人自扰 2020-11-29 02:02

We are learning about the Collection Interface and I was wondering if you all have any good advice for it\'s general use? What can you do with an Collection that you cannot

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 02:31

    It's easy if you think of it like this: Collections are better than object arrays in basically every way imaginable.

    You should prefer List over Foo[] whenever possible. Consider:

    • A collection can be mutable or immutable. A nonempty array must always be mutable.
    • A collection can be thread-safe; even concurrent. An array is never safe to publish to multiple threads.
    • A collection can allow or disallow null elements. An array must always permit null elements.
    • A collection is type-safe; an array is not. Because arrays "fake" covariance, ArrayStoreException can result at runtime.
    • A collection can hold a non-reifiable type (e.g. List> or List>). With an array you get compilation warnings and confusing runtime exceptions.
    • A collection has a fully fleshed-out API; an array has only set-at-index, get-at-index and length.
    • A collection can have views (unmodifiable, subList, filter...). No such luck for an array.
    • A list or set's equals, hashCode and toString methods do what users expect; those methods on an array do anything but what you expect -- a common source of bugs.
    • Because of all the reasons above, third-party libraries like Guava won't bother adding much additional support for arrays, focusing only on collections, so there is a network effect.

    Object arrays will never be first-class citizens in Java.

    A few of the reasons above are covered in much greater detail in Effective Java, Second Edition, starting at page 119.

    So, why would you ever use object arrays?

    • You have to interact with an API that uses them, and you can't fix that API
      • so convert to/from a List as close to that API as you can
    • You have a reliable benchmark that shows you're actually getting better performance with them
      • but benchmarks can lie, and often do
    • I can't think of any other reasons

提交回复
热议问题