ArrayList: Replace Remove with Add

xiaoxiao2021-03-06  59

ArrayList is the most common class in the Java container, which supports all methods defined in the List interface. The source code of ArrayList has been analyzed in front, and you may not be interested in it, here discussed it.

If you are interested in it, you can refer to: http://blog.9cbs.net/treeroot/archive/2004/09/16/107041.aspx

There are several common methods in ArrayList: GET (INT I): The efficiency is very high, and the array is ADD (Object Obj): Very high efficiency SET (int index, object obj): Very efficient ADD (int index, Object Obj ): Low efficiency, this method is less used! REMOVE (int index): Low efficiency Contains (Object Obj): low efficiency

If you know the implementation of ArrayList, you should know the efficiency of these methods. The top three methods are highly efficient. It is recommended to use, and three methods are the key to affect efficiency! In addition INDEXOF and LastIndexoF and Contains are the same because Contains are calling indexof directly. The situation is less than the amount of data, it is unable to do an actual test: There is an ArrayList, now remove certain elements, that is, filter lists.

Here are two ways: 1. Use the Remove method to delete elements that meet the conditions. 2. Regenerate an ArrayList to insert an element that does not satisfy the condition.

Use a very simple example here, an ArrayList contains natural numbers, I now delete the odd or even numbers. Because the original list is used to use the Remove method, it will regenerate one List every time.

Public class test {private static list testnew (int CNT) {list aa = new arraylist (); for (int i = 0; i

List b = new arraylist (100); // Production of new list for (INT i = 0; i

T1 = system.currenttimemillis (); for (int i = 0; i

Operating results are: List Size: 1using New List: 63msusing Remove Method: 31msNew VS Remove: 2.032258064516129: 1List Size: 10using New List: 16msusing Remove Method: 47msNew VS Remove: 0.3404255319148936: 1List Size: 100using New List: 15msusing Remove Method: 16msNew VS Remove: 0.9375: 1List Size: 1000using New List: 15msusing Remove Method: 63msNew VS Remove: 0.23809523809523808: 1List Size: 10000using New List: 31msusing Remove Method: 281msNew VS Remove: 0.1103202846975089: 1List Size: 100000using New List: 94msusing Remove Method: 2547msNew VS Remove: 0.03690616411464468: 1 It can be seen that when the List is less than 100, the efficiency is not equal, but if the ArrayList size is more obvious when the ArrayList size is greater than 1000! If ArrayList is relatively large, you can use the Add method to replace the Remove method to improve performance, that is, we must try to avoid using the remove method!

What needs to be described here is: We don't need to worry about the problem of memory space, because we don't generate new objects.

转载请注明原文地址:https://www.9cbs.com/read-112134.html

New Post(0)