简体   繁体   English

Java - arraylist 越界?

[英]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.我试过将交易的大小更改为其他数字,但我总是得到 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.当你执行new ArrayList<>(100)时,你实际上并没有创建一个包含 100 个元素的 List,100 只是底层数组的初始容量。

You might want to use add() method with index as an argument to ensure that your list actually has that much elements.您可能希望使用带有索引的add()方法作为参数来确保您的列表实际上有那么多元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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