Use an array when you are dealing with data that is:
在处理数据时使用数组:
fixed in size, or unlikely to grow much
固定的大小,或不可能增长太多
suitably large (more than 10, 50, 100 elements, depending on the algorithm)
适当大的(超过10,50,100个元素,根据算法)
you will be doing lots of indexing into it, i.e. you know you will often want the third element, or the fifth, or whatever.
你会做大量的索引,即你知道你会经常想要第三个元素,或第五,或任何。
Use a list for:
使用列表
variable length data lists .
可变长度数据表
that are mostly used as a stack or a queue or need to be iterated in its entirety
这主要是用来作为一个堆栈或队列或需要进行迭代的全部
when you do not want to write an expression to derive the ultimate array size for the declaration and you do not want to wastefully pick a large number
当你不想写一个表达式推导极限数组大小的声明,你不想浪费接大量
Use a hashmap for:
使用一个HashMap:
variable length data lists
可变长度数据表
that need to be indexed like an array would
这需要像一个数组索引
Array is Fixed in Size. Where , Collection is Grow able in nature.
Array stores homogeneous data . Where , Collection store both homogeneous as well as Heterogeneous data.数组存储均匀数据。在哪里,集合存储既有均匀也有异构数据。
In Array , there are no underlined Data Structures, whereas ,Collection has Underlined DS.在数组中,没有带下划线的数据结构,而集合有下划线的。
Array is recommended in performance , whereas Collection is not.数组中推荐的性能,而集合是不。
Array use more memory space compare to Collection.数组使用更多的内存空间比较集合。
如果你这样想,就很容易了:集合
比对象数组好,基本上可以想象。你应该更喜欢List<Foo>
over Foo[]
。考虑:
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.一个集合可以允许或不允许null元素。数组必须始终允许空元素。
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<Class<? extends E>> or List<Optional<T>>). 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.一个集合有一个有血有肉的API;数组只有设置指标,在指标和长度。
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.一个列表或集合的相等,hashCode和toString方法做用户期望;这些方法对数组做任何事,但你所期待的——错误的常见来源。
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.由于以上原因,第三方库像石榴不会增加多少额外的支持数组,只注重收藏,所以有一个网络效应。
本文出自 “Mr_Computer” 博客,请务必保留此出处http://caochun.blog.51cto.com/4497308/1699876
原文地址:http://caochun.blog.51cto.com/4497308/1699876