[英]How to remove an element from sorted ConcurrentNavigableMap with custom Comparator
The problem is when it's time to remove an element.问题是何时需要删除元素。 I tried on unsorted ConcurrentNavigableMap
and the element was successfully removed.我尝试了未排序的ConcurrentNavigableMap
并成功删除了该元素。 But on the sorted one cannot be removed.但在排序后无法删除。 Does anyone have any idea what the problem?有谁知道有什么问题?
private ConcurrentNavigableMap<String, Post> registeredPost=new ConcurrentSkipListMap<String,Post>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int i1=Integer.parseInt(o1);
int i2=Integer.parseInt(o2);
if(i1 >= i2){
return -1;
}else{
return 1;
}
};
});
public int deletePost(String postId) {
for(Iterator<Entry<String, Post>> it= registeredPost.entrySet().iterator();it.hasNext();) {
Entry<String,Post> e=it.next();
String temp=e.getKey();
if(temp.compareTo(postId)==0) {
registeredPost.remove(e.getKey());
}
return 0;
}
return 1;
}
Some issues:一些问题:
Equality of keys is determined by the comparator, your Comparator doesn't take equal elements into account.键的相等性由比较器决定,您的 Comparator 不考虑相等的元素。 You must return 0
if i1 == i2
- or use the Comparator
helper methods: Comparator.comparingInt(Integer::parseInt)
.如果i1 == i2
您必须返回0
- 或使用Comparator
辅助方法: Comparator.comparingInt(Integer::parseInt)
。 If you do not specify a comparator, the String.compareTo
method is used, which handles it correctly.如果未指定比较器,则使用String.compareTo
方法,该方法可以正确处理它。
You should remove Elements with it.remove()
method - otherwise you will get a ConcurrentModificationException
.您应该使用it.remove()
方法删除 Elements - 否则您将收到ConcurrentModificationException
。
The return statement is in the wrong place, as it has been pointed out.正如已经指出的那样,return 语句在错误的地方。
It seems you have add return 0
in the wrong place so that it will only iterate once and stop似乎您在错误的地方添加了return 0
以便它只会迭代一次并停止
public int deletePost(String postId) {
for(Iterator<Entry<String, Post>> it= registeredPost.entrySet().iterator();it.hasNext();) {
Entry<String,Post> e=it.next();
String temp=e.getKey();
if(temp.compareTo(postId)==0) {
registeredPost.remove(e.getKey());
return 0;//add return here?
}
}
return 1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.