I have found many related post here but couldn’t get my answer.Why this run-time error ?
static List<Integer>[] adj = (List<Integer>[]) new ArrayList[1000];
public static void main(String[] args) {
int edge, u, v, source;
Scanner input = new Scanner(System.in);
edge = input.nextInt();
for (int i = 0; i < edge; i++) {
u = input.nextInt();
v = input.nextInt();
adj[v].add(u); // Null pointer Exception
adj[u].add(v); // Null pointer Exception
}
First you need to initialize each elements of your array. Because until you do this, your reference in the array are not pointing to any object.
So, before that for-loop, you can add this one, to initialize your
Listinside theArray: –Also, it would be better if you have
List of Listrather than anarray of List. So, you can declare your list as: –An advantage of using an
ArrayListis that, you don’t have to limit your size at the beginning. So, you can add any number of elements. But, if it is a requirement to create a fixed size list, you can pass the size parameter in yourArrayListconstructor.And then you need to change your element adding code from: –
to: –