[英]Java: NullPointerException when trying to add object to BlockingQueue?
I found a similar question about a PriorityQueue, the error with that one was that it wasn't initialized correctly. 我发现了一个关于PriorityQueue的类似问题,该错误是未正确初始化。 I might have the same problem, but i can't figure out how to initialize it correctly!
我可能有同样的问题,但是我不知道如何正确初始化它!
As of now i just do: 到目前为止,我只是这样做:
BlockingQueue myQueue = null; BlockingQueue myQueue = null;
but that throws an exception as soon as i try to add something to the list. 但这会在我尝试向列表中添加内容时引发异常。
How do i correctly initialize a BlockingQueue? 如何正确初始化BlockingQueue?
BlockingQueue<E>
is an interface. BlockingQueue<E>
是一个接口。 You need to pick a specific implementation of that interface, such as ArrayBlockingQueue<E>
, and invoke one of its constructors like so: 您需要选择该接口的特定实现,例如
ArrayBlockingQueue<E>
,并按如下所示调用其构造函数之一:
BlockingQueue<E> myQueue = new ArrayBlockingQueue<E>(20);
If you're unsure what different types of blocking queues exist in the JDK, look under "All Known Implementing Classes" . 如果不确定JDK中存在哪些不同类型的阻塞队列,请查看“所有已知的实现类”下的内容 。
If you call any method on null you will get a null pointer exception. 如果在null上调用任何方法,则将获得null指针异常。 Try making a new ArrayBlockingQueue, which implements the interface.
尝试制作一个新的ArrayBlockingQueue来实现该接口。
Please read the javadocs which also has examples http://download.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html 请阅读javadocs,其中也包含示例http://download.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html
BlockingQueue blockingQueue = new ArrayBlockingQueue(100); BlockingQueueblockingQueue =新的ArrayBlockingQueue(100); // there are other implementations as well, in particular that uses a linked list and scales better than the array one.
//还有其他实现,尤其是使用链表并且比数组更好地扩展。
BlockingQueue
hold a certain type, for example BlockingQueue<String>
or something similar. BlockingQueue
保持某种类型,例如BlockingQueue<String>
或类似的东西。 BlockingQueue
, for example ArrayBlockingQueue<E>
. BlockingQueue
的实现来初始化变量,例如ArrayBlockingQueue<E>
。 So do something like: 因此,请执行以下操作:
BlockingQueue<MyObject> = new ArrayBlockingQueue<MyObject>();
and you'll be fine. 你会没事的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.