简体   繁体   中英

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. 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. You must return 0 if i1 == i2 - or use the Comparator helper methods: Comparator.comparingInt(Integer::parseInt) . If you do not specify a comparator, the String.compareTo method is used, which handles it correctly.

You should remove Elements with it.remove() method - otherwise you will get a ConcurrentModificationException .

The return statement is in the wrong place, as it has been pointed out.

It seems you have add return 0 in the wrong place so that it will only iterate once and stop

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM