I have a class called "Transaction.java", and I have an ArrayList with the newest five transactions. So the size of this ArrayList should always be between 0 and 5.
When there's a new transaction, I have to rotate all the entries in this ArrayList. Entry 4 becomes entry 3, entry 3 becomes entry 2, entry 2 becomes entry 1, entry 1 becomes entry 0 and entry 0 becomes the new transaction. The oldest one (the object with the index 4) is overwritten.
When trying to code this, I'm in trouble with ArrayIndexOutOfBoundsExceptions or NPEs because I do transactions.set(4, transactions.get(3));, even if there's nothing in transaction.get(3), and transaction.get(4) is empty as well!
This is a little snippet of my code:
for (int i = 4; i >= 0; i--) {
try {
if (i == 0) {
latestTransactions.set(i, newTransaction);
}
else {
latestTransactions.set(i, latestTransactions.get(i - 1));
}
} catch (Exception e) { // NPE / AIOOBE
e.printStackTrace();
}
}
The exception is thrown 5 times (that's how big the for-loop is) and nothing's set in the ArrayList.
Please try to keep calm and understandable, I'm new in the buiseness ^^