ArrayList按标识检索对象 [英] ArrayList Retrieve object by Id

查看:283
本文介绍了ArrayList按标识检索对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个非常简单的自定义对象的 ArrayList< Account> 。例如:

Suppose I have an ArrayList<Account> of my custom Objects which is very simple. For example:

class Account
{
public String Name;
public Integer Id;
}

我想检索特定的帐户对象,基于我的应用程序的许多部分中的 Id 参数。

I want to retrieve the particular Account object based on an Id parameter in many parts of my application. What would be best way of going about this ?

我想要扩展 ArrayList ,但我确定有必要更好的方法。

I was thinking of extending ArrayList but I am sure there must be better way.

推荐答案

听起来你真正想使用的是 Map ,它允许您基于键检索值。如果你坚持 ArrayList ,你唯一的选择是遍历整个列表并搜索对象。

It sounds like what you really want to use is a Map, which allows you to retrieve values based on a key. If you stick to ArrayList, your only option is to iterate through the whole list and search for the object.

类似:

for(Account account : accountsList) { 
   if(account.getId().equals(someId) { 
       //found it!
   }
}

accountsMap.get(someId)

这种操作是 Map 中的 O(1),vs

This sort of operation is O(1) in a Map, vs O(n) in a List.

$ b $ b

我一直在想扩展ArrayList,但我确定必须有
更好的方法。

I was thinking of extending ArrayList but I am sure there must be better way.

这是糟糕的设计。请阅读有效的Java 项目16,以便更好地了解为什么 - 或查看此文章

Generally speaking, this is poor design. Read Effective Java Item 16 for a better understanding as to why - or check out this article.

这篇关于ArrayList按标识检索对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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