I would like to read a graph from the input file and store it in list of arraylist.First list of the input file contains no.of vertices followed by number of edges. then the next line contains edges of the graph. I tried the following code and i'm getting error which is added at the end
import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
public class ReadGraph {
public static void main(String[] args) {
try {
int vertices,edges;
Scanner input = new Scanner(new File("in.txt"));
vertices = input.nextInt();
edges = input.nextInt();
List<Integer>[] tree = new List[vertices];
for (int i = 0; i < edges; i++) {
tree[input.nextInt()].add(input.nextInt());
}
System.out.println(vertices);
System.out.println(edges);
input.close();
System.out.println(tree);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Error
java.lang.ArrayIndexOutOfBoundsException: 2
at ReadGraph.main(ReadGraph.java:30)