Java:尝试将对象添加到 BlockingQueue 时出现 NullPointerException?
我发现了一个关于 PriorityQueue 的类似问题,该问题的错误是它没有正确初始化。我可能有同样的问题,但我不知道如何正确初始化它!
截至目前,我只是这样做:
BlockingQueue myQueue = null;
但当我尝试向列表中添加某些内容时,就会抛出异常。
如何正确初始化 BlockingQueue?
I found a similar question about a PriorityQueue, the error with that one was that it wasn't initialized correctly. 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;
but that throws an exception as soon as i try to add something to the list.
How do i correctly initialize a BlockingQueue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
BlockingQueue
是一个接口。您需要选择该接口的特定实现,例如ArrayBlockingQueue
,并调用其 构造函数像这样:如果您不确定 JDK 中存在哪些不同类型的阻塞队列,请查看 “所有已知的实现类”。
BlockingQueue<E>
is an interface. You need to pick a specific implementation of that interface, such asArrayBlockingQueue<E>
, and invoke one of its constructors like so:If you're unsure what different types of blocking queues exist in the JDK, look under "All Known Implementing Classes".
如果您对 null 调用任何方法,您将收到空指针异常。
尝试创建一个新的 ArrayBlockingQueue,它实现该接口。
If you call any method on null you will get a null pointer exception.
Try making a new ArrayBlockingQueue, which implements the interface.
请阅读 javadocs,其中也有示例
http://download.oracle.com/javase /6/docs/api/java/util/concurrent/BlockingQueue.html
BlockingQueue 阻塞队列 =
新的ArrayBlockingQueue(100); // 还有其他实现,特别是使用链表并且比数组具有更好的扩展性。
Please read the javadocs which also has examples
http://download.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html
BlockingQueue blockingQueue =
new ArrayBlockingQueue(100); // there are other implementations as well, in particular that uses a linked list and scales better than the array one.
BlockingQueue
保存某种类型,例如BlockingQueue
或类似的东西。BlockingQueue
的实现来初始化该变量,例如ArrayBlockingQueue
。所以做一些类似的事情:
你会没事的。
BlockingQueue
hold a certain type, for exampleBlockingQueue<String>
or something similar.BlockingQueue
, for exampleArrayBlockingQueue<E>
.So do something like:
and you'll be fine.