java - 无法添加到数组列表

标签 java list arraylist indexoutofboundsexception

我遇到了最奇怪的问题,可能有一个简单的解决方案。

我已经创建并初始化了一个列表,然后继续创建该列表类型的 4 个对象。在这些的构造函数中,它们将自己放入列表中。或者至少应该如此。我总是遇到越界异常,但我不明白为什么。我将列表的大小设置为 402(对于所有可能的 VK 值),但在控制台和调试中,它总是说它的大小为 0,无论我将其设置为多大或为空....

public class InputHandler implements KeyListener
{

public static List<Key> keyList = new ArrayList<Key>(KeyEvent.KEY_LAST);

public Key up = new Key(KeyEvent.VK_UP);
public Key down = new Key(KeyEvent.VK_DOWN);
public Key left = new Key(KeyEvent.VK_LEFT);
public Key right = new Key(KeyEvent.VK_RIGHT);


public class Key
    {

    public int keyCode;

    public Key(int defaultCode)
    {
        this.keyCode = defaultCode;
        keyList.add(keyCode,this);
    }

    public Key reMapKey(int newKey)
    {
        keyList.remove(keyCode);
        keyList.set(newKey, this);
        this.keyCode = newKey;
        return this;
    }

}

}

代码还有更多内容,但我尝试对其进行 SSCCE。

来自控制台的唯一有值(value)的信息是:

Exception in thread "RogueLoveMainThread" java.lang.IndexOutOfBoundsException: Index: 38, Size: 0

为我的愚蠢深表歉意

最佳答案

您创建了一个新的ArrayList 容量为 402,但在调用构造函数后,大小仍然为 0。来自 docs of the constructor call you're using :

public ArrayList(int initialCapacity)

Constructs an empty list with the specified initial capacity.

Parameters:
initialCapacity - the initial capacity of the list

来自 ArrayList 的文档本身:

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.

容量不是大小。

所以,一些选择:

  • 用空条目填充列表,直到获得所需的大小
  • 使用数组而不是列表(毕竟,您只需要它具有固定大小,对吧?)
  • 使用 Map<Integer, Key>相反

关于java - 无法添加到数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16448792/

相关文章:

java - 如何在将每个元素作为值集的列表中添加逗号

当设置两个条件部分满足彼此而没有 IF 语句或测试组且不作为元组时,Python 正则表达式返回两个结果

c# - 将值映射到列表中的项目并将新值添加到同一列表 C#

java - 用两个键映射一个值?

java - 获取嵌套ArrayList的频率

java - Maven 网络应用程序与 tomcat 5.5

java - 比较器compare()方法排序困惑

java - 为什么 Java 编译器不能正确推断继承?

python - 函数参数中的动态变量

java - 在Java中使用ArrayList按升序插入对象