简体   繁体   中英

Java - arraylist out of bounds?

I don't know what's going wrong here. As I understand it, it should be working:

public void deposit(int accNum, double balance)
    {
        for (int i = 0; i < numAccounts; i++)
        {
            if (accNum == accounts[i].getAccNum())
            {
                accounts[i].deposit(balance);
                Transaction temp = new Transaction(accNum, 1, balance, CurrentDateTime());
                if (this.transactions.size() <= 100)
                {
                    this.transactions.set(1, temp);
                }
                else
                {
                    this.transactions.remove(100);
                    this.transactions.set(1, temp);     //remove oldest
                    System.out.println("Please note that your oldest transaction has been overwritten.");
                }
            }
            else
            {
                System.out.println("No such account on record.");
            }
        }
    }

I am given the following error:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
    at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
    at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
    at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
    at java.base/java.util.Objects.checkIndex(Objects.java:373)
    at java.base/java.util.ArrayList.set(ArrayList.java:441)
    at Bank.deposit(Bank.java:145)         //in reference to this snippet, specifically at this.transactions.set(i, temp);
    at BankDemo1.main(BankDemo1.java:11)

Process finished with exit code 1

I've tried changing the size of transactions to be other numbers but I always get 0 is out of bounds for size 0.

transactions is defined as

private ArrayList<Transaction> transactions = new ArrayList<Transaction>(100);

This would be the first element put into transactions (as in, there is nothing in transactions before this when the method is called from the demo)

The relevant portion of code from Demo is

        testBank.deposit(1000, 150.25);

where the first number is an account number to be deposited into, and the second the amount to be deposited.

When you do new ArrayList<>(100) , you don't actually create a List with 100 elements, 100 is just the initial capacity of the underlying array.

You might want to use add() method with index as an argument to ensure that your list actually has that much elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM