简体   繁体   中英

Filtering list values, should I create a new list or delete values from the original one

Say I have a list that contains either single values, or value ranges. Now if I add a new value or a range to this list, it might overlap with none to multiple of the current values/ranges. All these overlapping objects should be combined to create a new instance, that should be added to the list, meanwhile the objects that got included in the new instance need to be deleted from the original list.

So my question is, should I really delete those objects from the list or create a new list on every iteration. That is, put to code:

Solution 1

for (Range newObj : newItems){
  Iterator it = oList.iterator();
  while (it.hasNext()){
    Range o = it.next();
    if (canCombine(newObj, o)){
      newObj = combine(newObj, o);
      it.remove();
    }
  }
  oList.add(newObj);
}

Solution 2

for (Range newObj : newItems){
  List newList = new ArrayList();
  for (Range o : oList){
    if (canCombine(newObj, o)){
      new = combine(newObj, o);
    } else {
      newList.add(o);
    }
  }
  newList.add(newObj);
  oList = newList;
}

Maybe another solution is even better. If so, kindly let me know.

I think you can avoid creating newList every time you iterate your newItems or you can avoid the creation of new list at all.

for (Object newObj : newItems){  
    for(int i=0;i<oList.size();i++){
        if (canCombine(newObj, oList.get(i))){ 
          newObj = combine(newObj,  oList.get(i)); 
          oList.remove(i);
        }    
      }  
      oList.add(newObj); 
    } 

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