使用 ArrayList 或 HashMap 提高速度 [英] Using ArrayList or HashMap for better speed
问题描述
我需要对象 A 的列表"或地图"....此列表将从另一个 ArrayList 添加.当 A 的 id
参数等于对象 A 时,认为对象 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 List
处理元素的线性表示,而 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
是你最好的打赌 - 如果您不关心排序,可能是 HashSet
.它提供 O(1) 时间基本操作,例如添加、删除、包含和大小.
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屋!