[英]Which Data Structure would be more suitable for the following task in Java?
每5
分钟,在第 20 分钟周期内,我需要检索数据。 目前,我正在使用地图数据结构。
有更好的数据结构吗? 每次读取和设置数据都要写入文件,防止程序重启和数据丢失。
例如,如果地图中的初始数据是:
{-1:"result1",-2:"result2",-3:"result3",-4:"result4"}
我想获取最后一个-4
周期的值"result4"
,并设置新值“result5”,这样更新后的地图将是:
{-1:"result5",-2:"result1",-3:"result2",-4:"result3"}
再次,我想获得最后一个-4
周期的值,即"result3"
,并设置新值"result6"
,所以地图将是:
{-1:"result6",-2:"result5",-3:"result1",-4:"result2"}
编码:
private static String getAndSaveValue(int a) {
//read the map from file
HashMap<Long,String> resultMap=getMapFromFile();
String value=resultMap.get(-4L);
for (Long i = 4L; i >= 2; i--){
resultMap.put(Long.parseLong(String.valueOf(i - 2 * i)),resultMap.get(1 - i));
}
resultMap.put(-1L,"result" + a);
//save the map to file
saveMapToFile(resultMap);
return value;
}
根据您的要求,我认为LinkedList数据结构将适合您的要求:
public class Test {
public static void main(String[] args) {
LinkedList<String> ls=new LinkedList<String>();
ls.push("result4");
ls.push("result3");
ls.push("result2");
ls.push("result1");
System.out.println(ls);
ls.push("result5"); //pushing new value
System.out.println("Last value:"+ls.pollLast()); //this will return `result4`
System.out.println(ls);
ls.push("result6"); //pushing new value
System.out.println("Last value:"+ls.pollLast()); // this will give you `result3`
System.out.println(ls);
}
}
输出:
[result1, result2, result3, result4]
Last value:result4
[result5, result1, result2, result3]
Last value:result3
[result6, result5, result1, result2]
从您的示例来看,您需要一个具有有限大小的FIFO数据结构。
JDK 中的Queue
接口没有有限的通用实现。 只有并发实现可以有大小限制。 但是如果你不打算在多线程环境中使用它,它就不是最好的选择,因为线程安全并不是免费的——并发收集速度较慢,而且还会让代码的读者感到困惑。
为了实现您的目标,我建议您通过包装ArrayDeque
来使用组合,这是Queue
的基于数组的实现,并且性能比LinkedList
更好。
请注意,这是一种不扩展ArrayDeque
( IS A关系)并覆盖其方法add()
和offer()
的首选方法,而是将其作为字段包含在类中( HAS A关系),以便所有方法调用您的类的实例将被转发到基础集合。 您可以在 Joshua Bloch 的Effective Java的“ Favor composition over inheritance ”项中找到有关此方法的更多信息。
public class BoundQueue<T> {
private Queue<T> queue;
private int limit;
public BoundQueue(int limit) {
this.queue = new ArrayDeque<>(limit);
this.limit = limit;
}
public void offer(T item) {
if (queue.size() == limit) {
queue.poll(); // or throw new IllegalStateException() depending on your needs
}
queue.add(item);
}
public T poll() {
return queue.poll();
}
public boolean isEmpty() {
return queue.isEmpty();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.