What is the difference between Collection and List in Java?

后端 未结 7 1897
无人共我
无人共我 2020-12-04 04:49

What is the difference between Collection and List in Java? When should I use which?

相关标签:
7条回答
  • 2020-12-04 05:41

    First off: a List is a Collection. It is a specialized Collection, however.

    A Collection is just that: a collection of items. You can add stuff, remove stuff, iterate over stuff and query how much stuff is in there.

    A List adds the information about a defined sequence of stuff to it: You can get the element at position n, you can add an element at position n, you can remove the element at position n.

    In a Collection you can't do that: "the 5th element in this collection" isn't defined, because there is no defined order.

    There are other specialized Collections as well, for example a Set which adds the feature that it will never contain the same element twice.

    0 讨论(0)
提交回复
热议问题