使用ArrayList或HashMap获得更好的速度 [英] Using ArrayList or HashMap for better speed

查看:335
本文介绍了使用ArrayList或HashMap获得更好的速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对象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.

我的直觉是您正在尝试在ListSet之间进行选择.

My gut feeling is that you're attempting to choose between a List and a Set.

如果您只想输入 unique 元素,或者更简洁地说,如果您只关心唯一值,那么最好使用某种Set-可能是如果您不关心订购. 它为O提供了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.

(有趣的是,HashSetHashMap支持,但提供类似于ArrayList的接口.)

(Interestingly enough, HashSet is backed by a HashMap, but provides an interface similar to ArrayList.)

这篇关于使用ArrayList或HashMap获得更好的速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆