LinkedList : Adding elements in constructor
Hi,
I am new to java and need help to understand following behavior I tried today.
I have a class variable defined like:
private static LinkedList<Integer> queue = new LinkedList<Integer>();
In Constructor I am adding some elemets as following:
Queue(){
for(int i=0;i<10;i++){
queue.add(i);
}
}
While in main its shows LinkedList as empty. So my question is why adding elements in constructor is not working for me.
Thanks in advance
Re: LinkedList : Adding elements in constructor
If you want help, you'll have to provide an SSCCE that demonstrates exactly what you're doing. For example, we have no idea what your main looks like, as you have not provided it. Don't forget the highlight tags.
Re: LinkedList : Adding elements in constructor
Hi ,
Folowing is the the code:
Code :
package datastructure;
import java.util.LinkedList;
public class QueueTest {
private static LinkedList<Integer> queue = new LinkedList<Integer>();
QueueTest(){ // static linked list's initialization in constructor
for(int i=0;i<10;i++){
System.out.println(i);
queue.add(i);
}
}
/**
* @param args
*/
public static void main(String[] args) {
int i=0;
// I am getting queue will no elements at this point
while(i <5){
i++;
System.out.println(queue.removeFirst()); // gives java.util.NoSuchElementException
}
}
}
Re: LinkedList : Adding elements in constructor
Where are your highlight tags? Unformatted code is very hard to read.
When do you call the QueueTest constructor?
Why are you referring to your queue variable in both a static and non-static context?