有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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 );

共 (6) 个答案

  1. # 1 楼答案

    你需要第一眼就添加而不是设置

    看看doc of set() method

    Throws: IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())

    您遇到了条件index >= size()

  2. # 2 楼答案

    我认为,很明显,ArrayList是使用默认容量(10)创建的,而您正试图访问它上面的索引(最多58个)

  3. # 3 楼答案

    最初,当您创建ArrayList的新实例时,ArrayList是空的:

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

    当您在ArrayList上调用set方法时,您试图替换一个现有的元素,该元素找不到,因为列表为空

    如果需要将元素添加到列表中,则应该使用add,而不是set

  4. # 4 楼答案

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

    创建一个空的arrayList

    {a1}方法

    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个元素(从0开始)。但是arraylist是空的,这就是为什么会出现异常

    您需要的是^{}方法:

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

    null添加到ArrayList的末尾

  5. # 5 楼答案

    查看类ArrayList的Java文档以及您使用的方法:

    方法集“用指定的元素替换列表中指定位置的元素。”

    在方法调用时,没有包含元素59的ArrayList。使用ArrayList()标准构造函数构造的ArrayList的初始大小为10

    可以使用构造函数ArrayList(int initialCapacity)

    请在此处查找文档:

    http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html