Deleting objects from an ArrayList in Java

前端 未结 13 2004
轮回少年
轮回少年 2020-12-15 03:14

I need to delete some objects from an ArrayList if they meet a condition and I\'m wondering which way could be more efficient.

Here\'s the situation: I

13条回答
  •  无人及你
    2020-12-15 04:13

    Whilst this is counter intuitive this is the way that i sped up this operation by a huge amount.

    Exactly what i was doing:

    ArrayList < HashMap < String , String >> results; // This has been filled with a whole bunch of results
    

    ArrayList < HashMap < String , String > > discard = findResultsToDiscard(results);

    results.removeall(discard);

    However the remove all method was taking upwards of 6 seconds (NOT including the method to get the discard results) to remove approximately 800 results from an array of 2000 (ish).

    I tried the iterator method suggested by gustafc and others on this post.

    This did speed up the operation slightly (down to about 4 seconds) however this was still not good enough. So i tried something risky...

     ArrayList < HashMap < String, String>> results;
    
      List < Integer > noIndex = getTheDiscardedIndexs(results);
    
    for (int j = noIndex.size()-1; j >= 0; j-- ){
        results.remove(noIndex.get(j).intValue());
    }
    

    whilst the getTheDiscardedIndexs save an array of index's rather then an array of HashMaps. This it turns out sped up removing objects much quicker ( about 0.1 of a second now) and will be more memory efficient as we dont need to create a large array of results to remove.

    Hope this helps someone.

提交回复
热议问题