ArrayList索引超出范围,但HashSet没有问题

问题描述

我有一个简单的Graph类,它使用列表数组跟踪哪些元素彼此链接。

从列表中删除元素时,我得到IndexOutOfBoundsException。代码下方给出了我的错误。

但是,如果我将集合从ArrayList<Integer>更改为HashSet<Integer>,则可以正常工作。

为什么Arraylist<Integer>类型在这里不起作用,但是HastSet<Integer>起作用?

删除这些集合中的元素的内部机制是什么?

class Graph {
    int v;

    ArrayList<Integer>[] connections;

    Graph(int v) {
        this.v = v;
        connections = new ArrayList[v];
        for (int i = 0; i < v; i++) {
            connections[i] = new ArrayList<>();
        }
    }

    void addConnection(int u,int v) {
        connections[u].add(v);
        connections[v].add(u);
    }

    void removeConnection(int u,int v) {
        connections[u].remove(v);
        connections[v].remove(u);
    }
}

class Main{
  
    public List<List<Integer>> criticalConnections(int n,List<List<Integer>> connections) {
        List<List<Integer>> result = new ArrayList<>();
        Graph graph = new Graph(n);
     
        for (List<Integer> connection : connections) {
            graph.addConnection(connection.get(0),connection.get(1));

    for (List<Integer> connection : connections) {
         graph.removeConnection(connection.get(0),connection.get(1));
         graph.addConnection(connection.get(0),connection.get(1));
    }
}

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 2
    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:372)

解决方法

您的问题是方法签名:

void removeConnection(int u,int v) { // <-- These should be Integer,not int
    connections[u].remove(v);
    connections[v].remove(u);
}

原因是List两个删除方法:

  1. remove(int index)删除索引为index的元素
  2. remove(Object object)查找并删除object

您正在调用版本1,但您想要版本2。

Set但是没有remove(int index)方法,因此java 自动将{>将int框化为Integer意向(如您所发现的)。

通过将方法签名更改为

void removeConnection(Integer u,Integer v)

调用了正确版本的remove()。如果将int传递给该方法,它将自动装箱到Integer,因此您无需更改此方法的用法。


这是一个极端的情况;仅当集合类型为Integer 且尝试自动装箱时,才会发生。但是,经常会出现这种情况,由于这种困惑,这种特殊情况值得您牢记在心,即使进行仔细调试也很难将其拾起。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...