Pergunta

I know it is always better to operate data in memory instead of file. Currently, I am putting all incoming data in a static ArrayList, and when that ArrayList has more than 80 entries, my program will save the contents of this ArrayList to a file and clear up this array for the next wave of coming data.

I wonder if it's better (or worse) to use Vector instead of ArrayList. If there is difference, which is better/worse? And in which case?

Here is my relevant code:

public class Exchange () {
    private static ArrayList<String> datain = new ArrayList<String> ();
    public static void addData(String s) {
        datain.add(s);
    }

    public static boolean checkSize() {
        if (datain.size() >= 80)
            return true;
        else
            return false;
    }

    public static void writeData() throws FileNotFoundException {
        PrintWriter pw = new PrintWriter(new File ("myfile.txt"));
        for (int i = 0; i < datain.size(); i++) {
            pw.println(datain.get(i);
        }
        pw.close();
    }

    public static void clear() {
        datain = new ArrayList<String>();
    }
}

P.S. This approach currently works fine, I am just wondering whether using vector will be better for this case. Also, if you see any bad design, feel free to point it out. Thanks!

Foi útil?

Solução

In the vast majority of cases, using ArrayList will suffice. The primary difference is that Vector is thread-safe, whilst ArrayList is not, but seeing as you aren't working with multiple threads, there is no reason to prefer Vector over ArrayList in your code

Outras dicas

This is how I would do it, unless I know there is a performance issue. Most of the cost is in the opening and closing of the file, so I would avoid doing that. I would also assume that appending is what you want.

public enum Logging {
    ; // no instances
    public static final String FILE_NAME = "myfile.txt";
    private static final PrintWriter pw;

    static {
        try {
            pw = new PrintWriter(new FileWriter(FILE_NAME, true));
        } catch (IOException ioe) {
            throw new AssertionError(ioe);
        }
    }

    public static void addData(String s) {
        pw.println(s);
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top