[英]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.