How to reset ArrayList in Java - Clear vs RemoveAll
Many times we want to reset an ArrayList for the reusing purpose, by resetting we mean clearing it or removing all elements. There are two ways to reset an ArrayList in Java, by using clear() method or calling removeAll(). If your ArrayList is small enough e.g. contains only 10 or 100 elements then you can use any of these two methods without worrying too much, but, if you have a huge list with lots of objects e.g. an ArrayList containing 10M entries, then choice of clear() vs removeAll() can make a huge difference in performance of your Java application. Sometimes it's even better to create a new ArrayList instead of resetting the old one, especially if resetting takes long time, but this also has a caveat, you need to make sure that old ArrayList is eligible for garbage collection, otherwise there is huge risk of java.lang.OutOfMemoryError: Java Heap Space. Coming back to clear() vs removeAll() method, you should always use clear(), because it gives you O(n) performance, while removeAll(Collection c) is worse, it gives O(n^2) performance, that's why you see huge difference in time taken by clearing a large ArrayList by these two methods. Things will be obvious, when you will run our example program and see the code of clear() and removeAll() method from JDK API. By the way, if you are in doubt, use clear() method and if not then always prefer clear over removeAll in Java.Read full article from How to reset ArrayList in Java - Clear vs RemoveAll
No comments:
Post a Comment