Reputation: 21
How to create vector of linked list in Java using Collections? So far I have written the following code:
Vector <LinkedList <Integer> > adj = new Vector<>();
However I am unable to figure out how to initialize the vector with head nodes of the linked list.
What I want is given an integer N
, I wish to initialize the vector with the values 0
to N-1
as the head nodes:
e.g given N = 4
vector ---> 0
1
2
3
So that later I can add members to the list when needed like :
vector ---> 0->2->3
1->3
2->0->1
3->1
Upvotes: 1
Views: 793
Reputation: 4809
With the code you have written, you have created an empty vector - you have to fill it with desired number of LinkedList instances (I am guessing you are a C++ programmer, where the vector would initialize "automatically"?). E.g. initialize your vector like this:
int N = 4;
Vector<LinkedList<Integer>> adj = new Vector<>(N); // N here isn't really needed, but it sets the initial capacity of the vector
for (int i = 0; i < 4; i++) {
ajd.add(new LinkedList<>());
}
Also, as Turing85 pointed out, you should use ArrayList
if you don't need the synchronization.
Upvotes: 1