Reputation: 2649
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:
id
isnt in the object already - insert itid
is in the object but the sid isnt the same - replace itid
in all
that isnt in the new list - remove itThis 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
Reputation: 170825
You can make it more efficient in two ways (not counting the one in Yogendra Singh's comment):
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
.
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
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