Search code examples
javavectorarraylistdata-management

Data operation in memory


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!


Solution

  • 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