Take a look at the following link:
http://snippetsofjosh.wordpress.com/tag/advantages-and-disadvantages-of-arraylist/
This one of the reasons why I always prefer to use Arrays instead of (Array)Lists. Still, this got me thinking about memory management and speed.
Hence I arrived at the following question:
What is the best way to store data from a file when you don't know the size of the file (/number of entries) (where best is defined as 'the least amount of computation time')
Below, I will present 3 different methods and I would like to know which one of them is best and why. For the clarity of the question, let's assume I must end up with an Array. Also, let's assume every line from our .txt file only has one entry (/one string). Also, for limiting the scope of the questions, I will limit this question to Java only.
Let's say we want to retrieve the following info from a file called words.txt
:
Hello
I
am
a
test
file
Method 1 - Double and dangerous
File read = new File("words.txt");
Scanner in = new Scanner(read);
int counter = 0;
while (in.hasNextLine())
{
in.nextLine();
counter++;
}
String[] data = new String[counter];
in = new Scanner(read);
int i = 0;
while (in.hasNextLine())
{
data[i] = in.nextLine();
i++;
}
Method 2 - Clear but redundant
File read = new File("words.txt");
Scanner in = new Scanner(read);
ArrayList<String> temporary = new ArrayList<String>();
while (in.hasNextLine())
{
temporary.add(in.nextLine());
}
String[] data = new String[temporary.size()];
for (int i = 0; i < temporary.size(); i++)
{
data[i] = temporary.get(i);
}
Method 3 - Short but rigid
File read = new File("words.txt");
FileReader reader = new FileReader(read);
String content = null;
char[] chars = new char[(int) read.length()];
reader.read(chars);
content = new String(chars);
String[] data = content.split(System.getProperty("line.separator"));
reader.close();
If you have an alternative way (which is even better) then please supply it below. Also, feel free to adjust my code where necessary.
Answer:
The fastest method for storing data in an array is the following method:
File read = new File("words.txt");
Scanner in = new Scanner(read);
ArrayList<String> temporary = new ArrayList<String>();
while (in.hasNextLine()) {
temporary.add(in.nextLine());
}
String[] data = temporary.toArray(new String[temporary.size()]);
And for Java 7+:
Path loc = Paths.get(URI.create("file:///Users/joe/FileTest.txt"));
List<String> lines = Files.readAllLines(loc, Charset.defaultCharset());
String[] array = lines.toArray(new String[lines.size()]);