gpt4 book ai didi

java - 是什么导致我的数组列表中出现此 ArrayOutOfBoundsException?

转载 作者:行者123 更新时间:2023-11-29 06:34:21 26 4
gpt4 key购买 nike

import java.util.*;
import java.util.ArrayList;

class MyHashTable<K extends Comparable<K>, E> {

private ArrayList<Entry<K,E>> bucket = new ArrayList<Entry<K,E>>();
private int bucketSize;
private int collisionCount = 0;

// Constructor that takes number of buckets as input
public MyHashTable( int len )
{
this.bucketSize = len;
for ( int i = 0; i < len; i++ )
{
bucket.set( i, null ); //ERROR APPEARS ON THIS LINE
}
}

当我从另一个方法调用时被调用:

MyHashTable<MyString, AnimalRecord> linearProbing = new MyHashTable<MyString, AnimalRecord>(59);
linearProbing.put( lion.name, lion );

最佳答案

private ArrayList<Entry<K,E>> bucket = new ArrayList<Entry<K,E>>();

创建一个空数组列表。

set 方法

Replaces the element at the specified position in this list with the specified element
Throws: IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())

所以

bucket.set( i, null );

尝试将 null 设置为 i第 th 个元素(从 0 开始)。但是 arraylist 是空的,这就是你得到异常的原因。

你想要的是 add 方法:

for ( int i = 0; i < len; i++ ) 
{
bucket.add(null);
}

添加 nullArrayList 的结尾.

关于java - 是什么导致我的数组列表中出现此 ArrayOutOfBoundsException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24389620/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com