ArrayList Retrieve object by Id

后端 未结 7 533
别跟我提以往
别跟我提以往 2020-12-16 12:49

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

class Account
{
public String Name;
public In         


        
7条回答
  •  时光取名叫无心
    2020-12-16 13:17

    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.

提交回复
热议问题