Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

java - ArrayList Retrieve object by Id

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

class Account
{
public String Name;
public Integer 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 ?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Something like:

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

versus

accountsMap.get(someId)

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...