Amar Amar - 20 days ago 7
Java Question

Get all elements in a LinkedList, exception

I need to get all the elements in the linked list. I do this by calling the

get()
method in my buffer (CharacterBuffer).

But every time I try to get the elements I get a nullPointerException. I don't know how to solve this.

public class Reader extends Thread {
private GUIMutex gui;
private CharacterBuffer buffer;

public Reader(GUIMutex gui, CharacterBuffer buffer) {
this.gui = gui;
this.buffer = buffer;
}

public void run() {
String data = "test";
while (true) {

try {
System.out.println(buffer.get());
gui.setReaderText(data + "\n");
Thread.sleep(1500);
} catch (InterruptedException e) {
}

}
}
}



public class CharacterBuffer {

private char ch;
private LinkedList buffer = new LinkedList();
private boolean filled = true;

public void put(char ch) {
buffer.addLast(ch);
buffer.removeFirst();
}

public Object get() throws InterruptedException {
while (buffer.isEmpty()) {
wait();
}

// return buffer.removeFirst();
return buffer.getFirst();
}

}

Answer

First thing You can not use char in Linked List it only accept Wrapper type. And in your put method you are adding and removing character at the same time. No value will remain in your linkedlist.

Comments