Java中的集合和列表有什么区别? [英] What is the difference between Collection and List in Java?
问题描述
Collection
和 List
在 Java 中有什么区别?我应该什么时候使用哪个?
What is the difference between Collection
and List
in Java? When should I use which?
推荐答案
首先:一个 List
是一个 集合
.然而,它是一个专门的Collection
.
Collection
就是:项目的集合.您可以添加内容、删除内容、迭代内容并查询其中有多少内容.
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
向其添加有关已定义内容序列的信息:您可以在位置 n 处获取元素,可以在位置 处添加元素n,你可以移除n位置的元素.
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.
在 Collection
中你不能这样做:这个集合中的第 5 个元素"没有定义,因为没有定义的顺序.
In a Collection
you can't do that: "the 5th element in this collection" isn't defined, because there is no defined order.
还有其他专门的集合,例如 Set
增加了永远不会包含相同元素两次的特性.
There are other specialized Collections as well, for example a Set
which adds the feature that it will never contain the same element twice.
这篇关于Java中的集合和列表有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!