当前位置: 移动技术网 > IT编程>开发语言>Java > 实现Java删除一个集合的多个元素

实现Java删除一个集合的多个元素

2019年07月22日  | 移动技术网IT编程  | 我要评论

问题

我需要从一个java的集合中,根据另一个集合的内容,删除第一个集合中不特定的元素。这看上去非常简单,但却遇到了问题。

这是我要写的方法的头部

private void screenblacknamelist(list<sharedboardsmswrapper> source, list<blacknamelistmodel> blacknamelist)

事情是这样子的。source集合中保存了一些显示用的数据元素。blacknamelist集合中保存的是黑名单列表。我们需要根据黑名单表,把source集合中黑名单用户的数据剔除掉。

这个问题的解决看上去非常简单。

我首先使用for each 语句进行删除。

for(sharedboardsmswrapper tmpsharedboardsmswrapper:source){

    for(blacknamelistmodel tmpblacknamelistmodel:blacknamelist){
      if(tmpsharedboardsmswrapper.getsource().equals(tmpblacknamelistmodel.getsource())){
        source.remove(tmpsharedboardsmswrapper);
        break;
      }

    }
  }

非常简单的问题!我暗笑,

测试…

令我意外的是,这段代码居然抛出了异常

java.util.concurrentmodificationexception。

查看jdk6手册

public class concurrentmodificationexception
extends runtimeexception

当方法检测到对象的并发修改,但不允许这种修改时,抛出此异常。

例如,某个线程在 collection 上进行迭代时,通常不允许另一个线性修改该 collection。通常在这些情况下,迭代的结果是不确定的。如果检测到这种行为,一些迭代器实现(包括 jre 提供的所有通用 collection 实现)可能选择抛出此异常。执行该操作的迭代器称为 快速失败 迭代器,因为迭代器很快就完全失败,而不会冒着在将来某个时间任意发生不确定行为的风险。

注意,此异常不会始终指出对象已经由 不同 线程并发修改。如果单线程发出违反对象协定的方法调用序列,则该对象可能抛出此异常。例如,如果线程使用快速失败迭代器在 collection 上迭代时直接修改该 collection,则迭代器将抛出此异常。

注意,迭代器的快速失败行为无法得到保证,因为一般来说,不可能对是否出现不同步并发修改做出任何硬性保证。快速失败操作会尽最大努力抛出 concurrentmodificationexception 。因此,为提高此类操作的正确性而编写一个依赖于此异常的程序是错误的做法,正确做法是concurrentmodificationexception  应该仅用于检测 bug。

java中的for each实际上使用的是iterator进行处理的。而iterator是不允许集合在iterator使用期间删除的。而我在for each时,从集合中删除了一个元素,这导致了iterator抛出了 concurrentmodificationexception

看来只有老老实实使用传统的for循环了!

for(int i=0;i<source.size();i++){
    sharedboardsmswrapper tmpsharedboardsmswrapper=source.get(i);
    for(int j=0;j<blacknamelist.size();j++){
      blacknamelistmodel tmpblacknamelistmodel=blacknamelist.get(j);
      if(tmpsharedboardsmswrapper.getsource().equals(tmpblacknamelistmodel.getsource())){
        source.remove(tmpsharedboardsmswrapper);
        break;
      }

    }

  }

这下应该没问题了吧!信心满满地按下测试…

晕!怎么回事,数据怎么过滤得不对?

debug跟踪后发现,原来,集合删除元素时,集合的size会变小,连带索引都会改变!

这可怎么办?我不会被这样一个小问题搞得没辙了吧!

使用iterator删除集合中的元素

查看jdk手册的iterator接口,看到它还有一个remove方法。

remove

void remove()

从迭代器指向的 collection 中移除迭代器返回的最后一个元素(可选操作)。每次调用 next 只能调用一次此方法。如果进行迭代时用调用此方法之外的其他方式修改了该迭代器所指向的 collection,则迭代器的行为是不确定的。

抛出:

unsupportedoperationexception - 如果迭代器不支持  remove 操作。

illegalstateexception - 如果尚未调用  next 方法,或者在上一次调用  next 方法之后已经调用了  remove 方法。

正确的最终代码:

/**
   *@paramsource
   *@paramblacknamelist
   */
  privatevoid screenblacknamelist(list<sharedboardsmswrapper> source, list<blacknamelistmodel> blacknamelist){
  iterator<sharedboardsmswrapper> sourceit=source.iterator();

  while(sourceit.hasnext()){
    sharedboardsmswrapper tmpsharedboardsmswrapper=sourceit.next();
    iterator<blacknamelistmodel> blacknamelistit=blacknamelist.iterator();
    while(blacknamelistit.hasnext()){
      blacknamelistmodel tmpblacknamelistmodel=blacknamelistit.next();
      if(tmpsharedboardsmswrapper.getsource().equals(tmpblacknamelistmodel.getsource())){
        sourceit.remove();
        break;
      }

    }

  }

  }

注意,一次iteratornext()方法,不能多次调用remove()方法。否则会抛出异常。

看来,删除集合中的元素,最简单的方法,就是使用iteratorremove()方法了!

让我们看看arraylist类提供的iterator是怎样实现的。

privateclass itr implements iterator<e> {
  /**
这是元素的索引,相当于一个指针,或者游标,利用它来访问list的数据元素。
   *indexofelementtobereturnedbysubsequentcalltonext.
   */
  intcursor = 0;

  /**
   *indexofelementreturnedbymostrecentcalltonextor
   *previous. resetto-1ifthiselementisdeletedbyacall
   *toremove.
最新元素的索引。如果已经删除了该元素,就设为-1
   */
  intlastret = -1;

  /**
外部类arraylist的属性:
protected transient int modcount = 0;
  它用于观察arraylist是否同时在被其他线程修改,如果不一致,那么就会抛出同步异常。
   *themodcountvaluethattheiteratorbelievesthatthebacking
   *listshouldhave. ifthisexpectationisviolated,theiterator
   *hasdetectedconcurrentmodification.
   */
  intexpectedmodcount = modcount;
//如果游标没有达到list的尺寸,那么就还有元素。
  publicboolean hasnext() {
      returncursor != size();
  }
//返回当前元素,然后游标+1。最近索引 也= 返回的元素的索引。
  public e next() {
      checkforcomodification();
    try {
    e next = get(cursor);
    lastret = cursor++;
    return next;
    } catch (indexoutofboundsexception e) {
    checkforcomodification();
    thrownew nosuchelementexception();
    }
  }
/*
删除元素,就是删除当前元素,并且把游标-1。因为,list会把后面的元素全部移前一位。
*/
  publicvoid remove() {
    if (lastret == -1)
    thrownew illegalstateexception();
      checkforcomodification();

    try {
    abstractlist.this.remove(lastret);
    if (lastret < cursor)
      cursor--;
    lastret = -1;
    expectedmodcount = modcount;
    } catch (indexoutofboundsexception e) {
    thrownew concurrentmodificationexception();
    }
  }

  finalvoid checkforcomodification() {
    if (modcount != expectedmodcount)
    thrownew concurrentmodificationexception();
  }
  }

总结

可以看到,iterator删除了元素,并且把游标重新置为正确的位子。只要没有其他线程同时改变该集合,就不会有任何问题。以上就是本文的全部内容了,希望对大家学习java有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网