I am trying to write a program which will help manage some data. So far, the user can create a new file using a "New File" Dialogue. After the user has entered some parameters, I create a new instance of a "File" class. My questions now is: How can I store multiple files (like tabs) in memory. I was thinking about using some sort of ArrayList as a variable in an "Application" class. What would be an ideal approch here?
You can use a map to store your files in memory.
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;
}
}
Then in your main class you can simply use the FileStorage class to manage your files
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");
}
The complexity to access or store file is O(1). It is better than a list for accessing a file.