Search code examples
javaandroidcollectionspojo

Storing array of POJOs - What is the better option in java?


I have POJOs parsed from JSON.

Account [] accounts; 

class Account {
  Integer number;
  String name;
  String location;
  Date started;
}

I get list of accounts from JSON API call. Jackson mapper maps the resulting JSON to above POJOs. I will need to do searching and other operations on these objects.

I am not sure how to store these to do the searching and to display them (in Android).

ArrayList
Map
HashTable
...

etc. Searching should be fast. I get about 500 accounts on an average. Mapping is done and I have the objects in an array now. But not sure how to go from here.

More over, I am fairly new to Java Collections and Generics. So any code example with direction would help.

Thanks!


Solution

  • If you're searching, and you can identify a single key on which to search, I'd recommend the HashMap, because it's O(1) for access if you have a key.

    HashTable is JDK 1.0 vintage; don't choose that.

    Here's an example, assuming that the number is unique and represents a good search choice:

    Account a = new Account(123456);
    Map<Integer, Account> accounts = new HashMap<Integer, Account>();
    accounts.put(a.getNumber(), a);
    

    To access, you use the number:

    Account b = accounts.get(123456);