kellykels21 kellykels21 - 1 year ago 50
Java Question

How to save the same object in an arraylist without overwriting the first line

What I would like to do is add new Transaction objects to the transactions Arraylist and save to a local file. Then pull that data back in and iterate over to populate a transcationTotal. Right now when i save a new transaction it overwrites the first object in the arraylist instead of saving the object to the next line.

Hope that was clear enough to understand thanks for your help!

//Enter Daily Transactions
public void enterTransactions() {
ArrayList<Transaction> transactions = new ArrayList();

System.out.print("Please enter the transaction amount: $");
Scanner amount = new Scanner(;
double transAmount = amount.nextDouble();
System.out.print("Please enter name for this transaction: ");
Scanner name = new Scanner(;
String transName = name.nextLine();
System.out.println("What week is this transaction going under?: ");
Scanner week = new Scanner(;
int transWeek = week.nextInt();
Transaction transaction = new Transaction(transName,transAmount,transWeek);


Iterator<Transaction> iterator = transactions.iterator();
while (iterator.hasNext()) {

Transaction i =;
int weekStat = i.getWeek();
if (weekStat == 1) {
double tAmount = i.getAmount();
transactionTotalWeekOne = transactionTotalWeekOne - transAmount;
} else if (weekStat == 2) {
double tAmount = i.getAmount();
transactionTotalWeekTwo = transactionTotalWeekTwo - transAmount;

try { // Catch errors in I/O if necessary.
// Open a file to write to, named SavedObj.sav.
FileOutputStream saveFile = new FileOutputStream("C:/temp/transactions_log.sav");

// Create an ObjectOutputStream to put objects into save file.
ObjectOutputStream save = new ObjectOutputStream(saveFile);

// Now we do the save.

// Close the file.
save.close(); // This also closes saveFile.
} catch (Exception exc) {
exc.printStackTrace(); // If there was an error, print the info.


Answer Source

Actually there is no overwriting on transaction objects. Your ArrayList always will have 1 element because you are recreating it every time enterTransactions() method called. There are some ways to prevent that.

  1. Move your transactions ArrayList out of the method and make it static.

  2. Give the transactions ArrayList to your enterTransactions(ArrayList transactions) method as a parameter.

Thus the list will not be recreated again and again.

P.S. You do not need to create a Scanner every time you need an input. Just one scanner is enough in your case.