sách gpt4 ai đã đi

java - 获取 OutOfBound 异常

In lại 作者:行者123 更新时间:2023-12-01 08:04:42 25 4
mua khóa gpt4 Nike

我正在编写一个java程序,它将电话簿信息存储在数组中。每当我尝试将一些条目放入该数组中时,都会出现 OutOfBound 异常。

private int size = 0;
private Entry[] entryList = new Entry[size];

public ArrayDirectory(){

}

@Ghi đè
public void Add(String surName, String initials, int telNumber) {

entryList[size] = new Entry(surName, initials, telNumber);
size++;


}

public static void main(String[] args){

ArrayDirectory directory = new ArrayDirectory();

directory.Add("Charles", "Johnson", 1234);

System.out.println(directory.entryList.length);
}

感谢您的关注

1 Câu trả lời

数组的大小是固定的。一旦您使用设定的大小创建它们,即它们可以容纳的最大元素数。

private int size = 0;
private Entry[] entryList = new Entry[size];

您创建了一个大小为 0 的数组,这意味着不能在其中设置任何元素。

private int size = 5;

允许您使用索引最多放入 5 个元素:0,1,2,3,4

更好的解决方案是通过 ArrayList 使用动态数组。当添加更多元素时,这将动态调整大小。

List entryList = new ArrayList();

entryList.add(new Entry());

关于java - 获取 OutOfBound 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22633165/

25 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com