![](/img/trans.png)
[英]How to store different objects of arrayList in memory and later retrieve them?
[英]How to store a list of objects to memory for later use
我正在嘗試編寫一個程序,將有助於管理一些數據。 到目前為止,用戶可以使用“新文件”對話框創建新文件。 用戶輸入一些參數后,我將創建“文件”類的新實例。 我現在的問題是:如何在內存中存儲多個文件(如選項卡)。 我正在考慮使用某種ArrayList作為“應用程序”類中的變量。 在這里什么是理想的選擇?
是的,您只需使用List
即可存儲實例
int maxfiles = 150; //You can set the length of the list, by default is 10
List<File> files = new ArrayList<File>(maxfiles);
//Your multiple files here
File file1 = null;
File file2 = null;
File file3 = null;
//Simply add it to the List
files.add(file1);
files.add(file2);
files.add(file3);
//And remove it by
files.remove(0); //Index
//Or remove all
files.clear();
您可以使用地圖將文件存儲在內存中。
public class FileStorage{
Map<String, File> fileMap;
public FileStorage(){
fileMap = new HashMap<String, File>();
}
public void addNewFile(File f, String fileName){
if (fileMap.get(fileName) != null){
// Do something if you do not want to erase previous file...
else{
fileMap.put(fileName, f);
}
}
public File getStoredFile(String fileName){
File f = fileMap.get(fileName);
if (f==null){
// alert user the file is not found.
}
return f;
}
}
然后在您的主類中,您可以簡單地使用FileStorage類來管理文件
public static void main(String[] args){
FileStorage fileStorage = new FileStorage();
// User create a new file
File file1 = new File();
fileStorage.addNewFile(file1, "file1"); // name can also be file1.getName()
[...]
// Later you can access the file
File storedFile = fileStorage.getStoredFile("file1");
}
訪問或存儲文件的復雜度為O(1)。 它比訪問文件列表要好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.