0

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.

3
  • 1
    What is stopping you to replace the all List itself with the new list? Commented Aug 16, 2013 at 16:03
  • why yo just not replace with the new list ?? Commented Aug 16, 2013 at 16:07
  • The sid = fetchSidFromDB(id); is just an example, it is much more complicated then that, that is what i'm try to avoid from. Commented Aug 16, 2013 at 16:14

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.