Nir
Nir

Reputation: 2649

refresh arraylist by another arraylist

I have this code:

public class Server{
  public static ArrayList<Server> all;

  public int id;
  public int sid;

  public Server(int id){
    thid.id = id;
    sid = fetchSidFromDB(id);
  }

  public Server(int id, int sid){
    thid.id = id;
    sid = sid;
  }

  public static void loadAll(){
    //Assume that I fill 'all' with the servers from the db
    all = new ArrayList<Server>();
  }

  //gets only a list of 'id's with out the sid
  public static void refreshAll(){
  }
}

//in the main
Server.loadAll();
Server.refreshAll();

I want that refreshAll will get new list from the db and do:

  1. If the id isnt in the object already - insert it
  2. If the id is in the object but the sid isnt the same - replace it
  3. If there is an id in all that isnt in the new list - remove it

This is simple, but as I see it I can only do it with:

for(...){
  for(...){
  }
  for(...){
}

One inside for for step 1&2 and one inside for for step 3.

I wonder if there's more efficient way.

Upvotes: 0

Views: 520

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170825

You can make it more efficient in two ways (not counting the one in Yogendra Singh's comment):

  1. Use a HashMap with id as the key instead. If you need the elements to be in the same order as you received them from the database, use LinkedHashMap.

  2. If you can make sure the lists are ordered by id, you can just use a single loop and advance over the second list with an iterator.

Upvotes: 1

Zolt&#225;n Haindrich
Zolt&#225;n Haindrich

Reputation: 1808

it looks like you are trying to cache database records...for that tasks there are tools already availiable, one of them is JPA, which can handle caching transparently

take a look for example on EclipeLink

Upvotes: 1

Related Questions