I got some homework in which I had to take the novel War and Peace and put it into a HashSet and TreeSet respectively. I had to time it, to check differences and my question is whether my implementation is good or not. If the way I calculate time is even accurate. I am using
System.currentMillis()
but I was debating with myself whether
System.nanoTime()
would be a better choice. I might just have misunderstood something about the assignment since this just seems way too easy to be the actual solution.
Just to clarify: The code works. I am questioning the efficiency of my implementation.
package SetExercise;
import java.io.*;
import java.util.*;
public class FileToSet {
public static void main(String[] args) {
HashSet<String> hs = new HashSet<>();
TreeSet<String> ts = new TreeSet<>();
long start = System.currentTimeMillis();
fileToHashSet("war-and-peace.txt", hs);
long end = System.currentTimeMillis();
long elapsed = end - start;
System.out.println("Total time HashSet (ms): " + elapsed);
start = System.currentTimeMillis();
fileToTreeSet("war-and-peace.txt", ts);
end = System.currentTimeMillis();
elapsed = end - start;
System.out.println("Total time TreeSet (ms): " + elapsed);
}
static void fileToHashSet(String path, HashSet<String> set) {
try {
BufferedReader in = new BufferedReader(new FileReader(path));
while(in.readLine() != null) {
String line = in.readLine();
set.add(line);
}
in.close();
} catch(FileNotFoundException fnfe) {
System.out.println(fnfe.getMessage());
} catch(IOException ioe) {
System.out.println(ioe.getMessage());
}
}
static void fileToTreeSet(String path, TreeSet<String> set) {
try {
BufferedReader in = new BufferedReader(new FileReader(path));
while(in.readLine() != null) {
String line = in.readLine();
set.add(line);
}
in.close();
} catch(FileNotFoundException fnfe) {
System.out.println(fnfe.getMessage());
} catch(IOException ioe) {
System.out.println(ioe.getMessage());
}
}
}