使用ArrayList或HashMap获得更好的速度 [英] Using ArrayList or HashMap for better speed
问题描述
我需要对象A的列表"或地图".此列表将从另一个ArrayList中添加.当A的id
参数等于时,认为对象A等于另一个对象.
I need a 'List' or 'Map',... of object A. This list will be added from another ArrayList. Object A is considered to be equal to another when id
parameter of A equals.
我的问题是我只想添加列表中不存在的对象.我不知道在这两种实现方式之间.使用ArrayList或HashMap
My problem is I only want add an object that does not exist in my List. I wonder between the two alternatives for implementation. Using ArrayList or HashMap
1. ArrayList:
for (A a: source) {if (! (a in ArrayList)) addToArrayList();}
2. HashMap <id, A>
for (A a: source) {hasmap.put (a.id, a)}
添加大量(超过1000个对象或更多对象)的速度会更快 我的问题有更好的模式吗?
Which will give better speed to add a large number (over 1000 objects, or bigger number of object) Is there a better pattern for my problem???
推荐答案
首先,我要大胆地指出这些是两个完全不同的数据结构. A Map
处理键对值.
First, I'm going to go out on a limb and state that these are two completely different data structures. A List
deals with a linear representation of elements, and a Map
deals with key-pair values.
我的直觉是您正在尝试在List
和Set
之间进行选择.
My gut feeling is that you're attempting to choose between a List
and a Set
.
如果您只想输入 unique 元素,或者更简洁地说,如果您只关心唯一值,那么最好使用某种Set
-可能是
If you wish to only enter unique elements, or to put it more succinctly, if you only care about unique values, then a Set
of some kind is your best bet - probably HashSet
if you don't care about ordering. It provides O(1) time for the basic operations, such as add, remove, contains, and size.
(有趣的是,HashSet
由HashMap
支持,但提供类似于ArrayList
的接口.)
(Interestingly enough, HashSet
is backed by a HashMap
, but provides an interface similar to ArrayList
.)
这篇关于使用ArrayList或HashMap获得更好的速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!