[英]refresh arraylist by another arraylist
我有这个代码:
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();
我想refreshAll
将从数据库中获取新列表并执行:
id
不在对象中 - 插入它 id
在对象中但sid不相同 - 替换它 id
的all
,在新的列表心不是-删除 这很简单,但正如我所看到的,我只能这样做:
for(...){
for(...){
}
for(...){
}
一个内部for
用于步骤1和2和一个内部for
用于步骤3。
我想知道是否有更有效的方法。
看起来你正在尝试缓存数据库记录...对于那些任务,已经有可用的工具,其中一个是JPA
,它可以透明地处理缓存
你可以通过两种方式提高效率(不计算Yogendra Singh评论中的那个):
使用带有id
作为键的HashMap
。 如果您需要的元素与从数据库中接收的元素的顺序相同,请使用LinkedHashMap
。
如果您可以确保列表按id
排序,则可以使用单个循环并使用迭代器前进到第二个列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.