Four methods of Java ArrayList traversal and the usage of ArrayList class in Java

Four methods of Java ArrayList traversal and the usage of ArrayList class in Java

PS: usage of ArrayList class in Java

1. What is ArrayList

ArrayList is a legendary dynamic array. In MSDN, it is a complex version of array. It provides the following benefits:

Dynamic increase and decrease elements

Icollection and IList interfaces are implemented

Flexible setting of array size

2. How to use ArrayList

The simplest example:

This is a simple example. Although it does not contain all the methods of ArrayList, it can reflect the most commonly used usage of ArrayList

3. ArrayList important methods and properties

1) Constructor

ArrayList provides three constructors: public arraylist(); The default constructor will initialize the internal array public ArrayList (icollection) with the default (16) size; Construct with an icollection object, and add the elements of the collection to ArrayList public ArrayList (int); Initializes the internal array with the specified size

2) Issynchronized property and ArrayList Synchronized method

The issynchronized property indicates whether the current ArrayList instance supports thread synchronization The synchronized static method will return an encapsulation of thread synchronization of ArrayList.

If a non thread synchronized instance is used, you need to manually call lock to maintain thread synchronization when accessing multiple threads, for example:

The syncroot attribute is itself, but in order to meet the syncroot definition of icollection,

Syncroot is still used here to keep the source code normative

If you use ArrayList The instance returned by the synchronized method does not need to consider thread synchronization. This instance itself is thread safe. In fact, ArrayList implements an internal class to ensure thread synchronization, ArrayList Synchronized returns an instance of this class. Each attribute in it uses the lock keyword to ensure thread synchronization.

3) Count property and capacity property

The count attribute is the number of elements contained in the current ArrayList. This attribute is read-only. The capacity property is the maximum quantity that ArrayList can contain at present. You can set this property manually, but an exception will be thrown when it is set to less than the count value.

4)Add、AddRange、Remove、RemoveAt、RemoveRange、Insert、InsertRange

These methods are similar

The add method is used to add an element to the end of the current list. The addrange method is used to add a batch of elements to the end of the current list. The remove method is used to delete an element, delete it through the reference of the element itself. The removeat method is used to delete an element, and delete it through the index value. The removelange method is used to delete a batch of elements, Insert is used to add an element to the specified location by specifying the starting index and the number of deleted elements. The elements behind the list move back in turn. Insertrange is used to add a batch of elements from the specified location, and the elements behind the list move back in turn

In addition, there are several similar methods:

The clear method is used to clear all existing elements. The contains method is used to find out whether an object is in the list

I won't be cumbersome one by one. You can check MSDN, which is more detailed

5) Trimsize method

This method is used to fix the ArrayList to the size of the actual element. When the dynamic array element is determined not to be added, this method can be called to free up the spare memory.

6) ToArray method

This method copies the ArrayList elements into a new array.

4. ArrayList and array conversion

Example 1:

Example 2:

The above describes two methods of converting from ArrayList to array

Example 3:

Unlike arrays, it can be converted into an object array, so adding elements of different types to the ArrayList will not make an error. However, when calling the ArrayList method, either pass the type or object type that all elements can be transformed correctly, or an exception that cannot be transformed will be thrown.

5. ArrayList best use recommendations

In this section, we will discuss the difference between ArrayList and array and the efficiency of ArrayList

1) ArrayList is a complex version of array

ArrayList encapsulates an array of object type. In a general sense, it is not fundamentally different from an array

Set the size of the actual element. When the dynamic array element is determined not to be added, this method can be called to free up the spare memory.

6) ToArray method

This method copies the ArrayList elements into a new array.

4. ArrayList and array conversion

Example 1:

Example 2:

The above describes two methods of converting from ArrayList to array

Example 3:

Unlike arrays, it can be converted into an object array, so adding elements of different types to the ArrayList will not make an error. However, when calling the ArrayList method, either pass the type or object type that all elements can be transformed correctly, or an exception that cannot be transformed will be thrown.

5. ArrayList best use recommendations

In this section, we will discuss the difference between ArrayList and array and the efficiency of ArrayList

1) ArrayList is a complex version of array

ArrayList internally encapsulates an array of object type. In a general sense, it is not fundamentally different from array. Even many methods of ArrayList, such as index, indexof, contains, sort, etc., directly call the corresponding method of array on the basis of internal array.

2) Influence of internal object type

For general reference types, this part does not have a great impact, but for value types, adding and modifying elements to ArrayList will cause boxing and unpacking operations. Frequent operations may affect some efficiency. But just for most people, most applications use arrays of value types. There is no way to eliminate this effect. Unless you don't use it, you will have to bear part of the efficiency loss, but the loss will not be very large.

3) Array expansion

This is a factor that has a great impact on the efficiency of ArrayList. Whenever the methods of adding elements such as add, addrange, insert and insertrange are executed, it will check whether the capacity of the internal array is insufficient. If so, it will rebuild an array with twice the current capacity, copy the old elements into the new array, and then discard the old groups. The capacity expansion operation at this critical point should affect the efficiency.

Example 1: for example, when a data with 200 elements is dynamically added to an ArrayList with a default size of 16 elements, it will go through the following steps:

16*2*2*2*2 = 256

The final requirements can only be met after four expansion. If you start with:

ArrayList List = new ArrayList( 210 ); Creating an ArrayList in this way will not only reduce the number of array creation and copy operations four times, but also reduce memory usage.

Example 2: an ArrayList is created with an estimated 30 elements:

ArrayList List = new ArrayList(30);

In the execution process, if 31 elements are added, the array will be expanded to the size of 60 elements, and no new elements will be added at this time. If the trimsize method is called, there will be an expansion operation and 29 element size space will be wasted. If at this time, use:

ArrayList List = new ArrayList(40);

Then everything is solved. Therefore, correctly estimating possible elements and calling trimsize method at an appropriate time is an important way to improve the efficiency of ArrayList.

4) Frequently call indexof, contains and other methods (sort, binarysearch, etc.)

Efficiency loss caused by optimized methods (not listed here). First of all, we need to make it clear that ArrayList is a dynamic array, which does not include algorithms for quick access through key or value. Therefore, in fact, calling indexof, contains and other methods is a simple loop to find elements, Therefore, calling such methods frequently is not faster than writing loops and optimizing them. If there are requirements in this regard, it is recommended to use a collection of key value pairs such as hashtable or SortedList.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>