当前位置: 代码迷 >> J2SE >> removeAll方法的有关问题
  详细解决方案

removeAll方法的有关问题

热度:93   发布时间:2016-04-24 13:03:10.0
removeAll方法的问题
代码:
List<DocListDto> docListDtos = docListDao.selectArchiveAll(typeID,null);

List<DocListDto> docListDtosSmall = new ArrayList<DocListDto>();
DocListDto docListDto = null;
......
for (ArchiveListDto archiveListDto : archiveListDtos) {
docListDto = docListDao.selectArchiveDocListDto(archiveListDto.getTypeID(), archiveListDto.getDocId());
docListDtosSmall.add(docListDto);
}
boolean bl = docListDtos.removeAll(docListDtosSmall); //返回false

List都是ArrayList,docListDtosSmall是docListDtos的子集,我想从docListDtos中移除docListDtosSmall中的内容,但是使用removeAll方法不好用,
似乎只有两个集合的交集元素持有相同的引用时removeAll才起作用。

有没有什么高效的办法让我做到这一点?

------解决方案--------------------
直接从数据库中查出符合条件的
------解决方案--------------------
要么在数据库直接SQL语句操作,SQL语句很强大的,
或者用set,也很强大的
------解决方案--------------------
DocListDto是什么类型的?Object?
------解决方案--------------------
这个问题不是很难,我们仔细分析一下list及其子类ArrayList中调用的removeAll方法,发现其来自AbstractCollection类,其实现如下,
Java code
    public boolean retainAll(Collection<?> c) {    boolean modified = false;    Iterator<E> e = iterator();    while (e.hasNext()) {        if (!c.contains(e.next())) {        e.remove();        modified = true;        }    }    return modified;    }
------解决方案--------------------
先if contains判断存在另一个list里的元素,然后remove
------解决方案--------------------
4楼讲的很详细了 不过 建议在数据库里面过滤