I have a simple Graph class, which tracks which elements are linked to eachother using an array of Lists.
I am getting IndexOutOfBoundsException
when removing an element from the list. My error is given below the code.
But if I change the collection from ArrayList<Integer>
to HashSet<Integer>
, it works fine.
Why does Arraylist<Integer>
type not work here but HastSet<Integer>
works?
And what is the internal mechanism of removing elements of these collections?
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)