开发者_如何学JAVAI wrote a java class which reads a file and stores each line in an arraylist. I want to access this arraylist large number of times. Everytime the class is called to access the arraylist, it reads the file again. I want the file to be read once and then access the arraylist multiple times. How can I do this?
Store it in a field of the class. I.e.:
public class Foo {
private List<String> list;
public List<String> readData() {
if (list != null) {
return list;
}
// do the reading.
}
}
Note that if this is used in a multithreaded environment you'd have to take extra measures. For example put synchronized
on the method.
As Peter noted, if you can read multiple files, then you can use a Map<String, List<String>>
Another note is that you should use only one instance of this class. If you create multiple instances you won't have the desired effect.
It sounds like you should be reading the file on construction of the class rather than when accessing it. That doesn't necessarily mean in the constructor, mind you - you may well want to have a static factory method that reads the files into an ArrayList
, and then passes that list to the real constructor. This would make the class easier to test (and use in other tests).
Then you only need to create the class once, and make the rest of your code use the same instance. Note that this doesn't require use of the singleton pattern, which would itself make testing harder. It just means propagating the instance to all the code that needs it.
Maybe you need to make a singleton? Then you will read the file only once - when you create a really new instance of class.
If its a web application, maybe you would consider storing it in the ServletContext or in the user HttpSession depending on how much does the file changes
精彩评论