如何解决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
有两个删除方法:
- remove(int index)删除索引为
index
的元素 - remove(Object object)查找并删除
object
您正在调用版本1,但您想要版本2。
Set
但是没有remove(int index)
方法,因此java 自动将{>将int
框化为Integer
的意向(如您所发现的)。
通过将方法签名更改为
void removeConnection(Integer u,Integer v)
调用了正确版本的remove()
。如果将int
传递给该方法,它将自动装箱到Integer
,因此您无需更改此方法的用法。
这是一个极端的情况;仅当集合类型为Integer
且尝试自动装箱时,才会发生。但是,经常会出现这种情况,由于这种困惑,这种特殊情况值得您牢记在心,即使进行仔细调试也很难将其拾起。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。