LinkedList.pollLast() 抛出 NullPointerException
我使用 Java 6 Collections API。我需要一个只包含 N 个元素的集合。我的意思是,如果我添加新元素并且集合已经有 N 个元素,那么应该删除最后一个元素,并将新元素添加到集合的头部。我有以下代码片段来执行此操作:
class A {
int N = 100;
Deque dq = new LinkedList();
void add(Object o) {
synchronized (o) {
if (dq.size() == N) {
dq.pollLast();
}
dq.add(o);
}
}
Deque getDq() {
return new LinkedList(dq);
}
}
类型 A 的对象可以同时被许多用户访问以添加新元素。在实践中,我得到了 NullPointerException:
Caused by: java.lang.NullPointerException
at java.util.LinkedList.remove(LinkedList.java:790)
at java.util.LinkedList.removeLast(LinkedList.java:144)
at java.util.LinkedList.pollLast(LinkedList.java:573)
at A.add(A.java:9)
Deque.pollLast() 合约没有提及任何有关 NullPointerException 的内容:
检索并删除最后一个元素 此列表的,或者如果此则返回 null 列表为空。
元素的添加也是同步的。
有谁知道例外的原因可能是什么?
感谢您的任何想法
I use Java 6 Collecetions API. I need a collection that should have only N elements. I mean that if I add new element and collection already have N elements than the last element should be removed and new one add in the head of collection. I have following code fragment to do it:
class A {
int N = 100;
Deque dq = new LinkedList();
void add(Object o) {
synchronized (o) {
if (dq.size() == N) {
dq.pollLast();
}
dq.add(o);
}
}
Deque getDq() {
return new LinkedList(dq);
}
}
Object with type A can be accessed many users in the same time to add new element. In practice I got NullPointerException with it:
Caused by: java.lang.NullPointerException
at java.util.LinkedList.remove(LinkedList.java:790)
at java.util.LinkedList.removeLast(LinkedList.java:144)
at java.util.LinkedList.pollLast(LinkedList.java:573)
at A.add(A.java:9)
Deque.pollLast() contract doesn't say anything about NullPointerException:
Retrieves and removes the last element
of this list, or returns null if this
list is empty.
Also adding of elements is synchronized.
Does anyone know what is reason of exception could be?
Thanks for any ideas
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我猜同步是在错误的对象上完成的!它应该是
dq
而不是o
!I guess the sycronization is done on the wrong object! It should be
dq
but noto
!我已经使用以下测试运行了添加的代码
,并且一切似乎都正常工作。您能否提供有关获得 NPE 时申请状态的更多详细信息?您要添加的对象是什么?当时Dequeue是什么状态?
另外,你提到
您的代码不会这样做。现在,它已添加到集合的尾部。要将其添加到头部,请更改
为
I've run your code adding using the following test
And it all seems to work correctly. Can you provide more details on the state of the application when you get the NPE? What is the object you are trying to add? What is the state of the Dequeue at that time?
Also, you mentioned
Your code doesn't do that. Right now, it adds to the tail of the collection. To add it to the head, change
to
请参阅 此 javadoc 它说
首先会删除对象所以如果它是 null 则抛出 NullPointerException:
因此使 add(..) 方法同步并在 dq.pollLast(); 之前检查大小
see this javadoc it says
first it removes object so if it is null then throws NullPointerException:
so make add(..) method synchronized and check for size before
dq.pollLast();