How to use the ArrayList class in Java

  • 2020-04-01 02:35:53
  • OfStack

Usage of the ArrayList class in Java

1. What is an ArrayList

ArrayList is the legendary dynamic Array, or complex version of Array as it is called in MSDN, and it offers the following benefits:
Dynamic addition and subtraction of elements
ICollection and IList interface are implemented
Flexible array size Settings

2. How to use ArrayList

The simplest example:

ArrayList List = new ArrayList();
For (int I = 0; I < 10; I++) // add 10 Int elements to the array
List. Add (I);
/ /.. The program does some processing
List. The RemoveAt (5); // removes the sixth element
For (int I = 0; I < 3; I++) // add 3 more elements
List. Add (I + 20);
Int32 [] values = (Int32 []) List. The ToArray (typeof (Int32)); // returns the array that the ArrayList contains

This is a simple example that does not include all of the ArrayList methods, but reflects the most common usage of ArrayList

3. Important methods and properties of ArrayList

1) constructor

ArrayList provides three constructors:
Public ArrayList ();
The default constructor initializes the inner array at the default size (16)
Public ArrayList (ICollection);
Construct it with an ICollection object and add the elements of the collection to the ArrayList
Public ArrayList (int);
Initializes the inner array with the specified size

2) IsSynchronized properties and arraylist.synchronized methods

The IsSynchronized property indicates whether the current ArrayList instance supports thread synchronization, while the arraylist.synchronized static method returns a wrapper around the thread synchronization of the ArrayList.
If you use a non-thread-synchronized instance, you need to manually call the lock to keep the threads synchronized during multi-threaded access, for example:
ArrayList list = new ArrayList();
/ /...
Lock (list.syncroot) // when the ArrayList is wrapped for non-threads, the SyncRoot attribute is itself, but SyncRoot is used here to keep the source code regular in order to satisfy the SyncRoot definition of ICollection
{
List.Add(" Add a Item ");
}

If you use the ArrayList. Synchronized method returns an instance of, so you don't have to consider the problem of thread synchronization, the instance itself is thread-safe, actually inside the ArrayList implements a guarantee thread synchronization inner class, ArrayList. Synchronized return is an instance of the class, it's the lock key of each attribute is used to guarantee the thread synchronization.

3) Count attribute and Capacity attribute

The Count attribute, which is read-only, is the number of elements currently contained in the ArrayList.
The Capacity property is the maximum amount that an ArrayList can currently contain. This property can be set manually, but an exception is thrown when set to less than the value of Count.

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 Remove an element by reference to the element itself
The RemoveAt method is used to remove an element, by index value
RemoveRange is used to remove a batch of elements, by specifying the number of indexes to start with and the number of deletions
Insert is used to add an element to the specified location, with the elements following the list moving back in turn
InsertRange is used to add a batch of elements from the specified location, with the elements following the list moving 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 if an object is in the list

I'm not going to bother you with the rest, but you can look at MSDN, which is more detailed

5) TrimSize method

This method is used to fix the ArrayList to the size of the actual element and is called to free up free memory when the dynamic array element is determined not to be added.

6) ToArray method

This method copies the elements of the ArrayList into a new array.

4. ArrayList and array conversion

Case 1:
ArrayList List = new ArrayList();
List. The Add (1);
List. Add (2);
List. Add (3);

Int32 [] values = (Int32 []) List. The ToArray (typeof (Int32));

Example 2:
ArrayList List = new ArrayList();
List. The Add (1);
List. Add (2);
List. Add (3);

Int32[] values = new Int32[list.count];
List. CopyTo (values);

Two methods of converting from an ArrayList to an array are described above

Example 3:
ArrayList List = new ArrayList();
List. The Add (" string ");
List. The Add (1);
// add different types of elements to the array

Object [] values = List. ToArray (typeof (object)); / / right
String [] values = (string []) List. The ToArray (typeof (string)); / / error

It is different from an array, because it can be converted to an Object array, so it is not wrong to add different types of elements to the ArrayList. However, when the ArrayList method is called, it should either pass the type that all elements can be converted correctly or the Object type, or it will throw an exception that cannot be transformed.

5. Suggestions for the best use of ArrayList

In this section, we will discuss the difference between an ArrayList and an array, and the efficiency of an ArrayList
    (1) ArrayList is a complex version of Array
ArrayList internally encapsulates an Array of type Object. In a general sense, it is not fundamentally different from an Array. Many methods of ArrayList, such as Index, IndexOf, Contains, Sort, etc., call the corresponding method of Array directly on the basis of an internal Array.
    (2) the influence of internal Object type
                  For general reference types, this part of the impact is not very big, but for value types, adding and modifying elements to the ArrayList causes boxing and unboxing operations, and frequent operations may affect some efficiency.
But 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 some loss of efficiency, which is not very large.
    (3) array expansion
This is a factor that has a great impact on the efficiency of ArrayList.
Whenever the Add, AddRange method of adding elements, Insert and InsertRange, will check the internal array capacity is not enough, if it is, it will double the current capacity to rebuild an array to Copy the old elements to the new array, then discarding the old array, in this critical point of expansion, is affecting the efficiency of the comparison should be.
          Example 1: for example, a data that may have 200 elements is dynamically added to an ArrayList that is created with the default size of 16 elements and will go through:
16 * 2 * 2 * 2 * 2   =   256
Four times of capacity expansion will meet the final requirements, so if the beginning with:
ArrayList  List  =   New  ArrayList (  210  ) ;
ArrayList is created in a way that not only reduces group creation and Copy operations by four times, but also reduces memory usage.

          Example 2: an ArrayList is created with an expectation of 30 elements:
ArrayList  List  =   New  ArrayList (30);
In the process of execution, 31 elements are added, then the array will expand to the size of 60 elements, and there will be no new elements added in this time, and there is no TrimSize method called, then there is one expansion operation, and wasted 29 element size space. If so, use:
ArrayList  List  =   New  ArrayList (40);
Then everything is settled.
Therefore, correctly estimating the possible elements and calling TrimSize method when appropriate is an important way to improve the use efficiency of ArrayList.
      (4) efficiency loss caused by frequent calls to methods such as IndexOf, Contains, etc. (Sort, BinarySearch, etc., which are optimized and not in this column)
First of all, we have to be clear, the ArrayList is a dynamic array, it does not include through Key or Value algorithm of fast access, so in fact call IndexOf, the Contains method is to perform simple cycle to look for the element, so often call this kind of method does not write cycle than yourself and make a little optimization to fast, if has this aspect of the requirements, recommend the use of Hashtable or SortedList collection of Key/Value pair.
ArrayList  Al = new  ArrayList ();

Al. The Add (" How ");
Al. The Add (" are ");
Al. Add (" you!" );

Al. Add (100);
Al. Add (200);
Al. Add (300);

Al. Add (1.2);
Al. Add (22.8);

.

// the first kind of traversal   ArrayList  Object method
The foreach (object  O  In  Al)
{
The Console. Write (o.T oString () + " " );
}

// the second kind of traversal   ArrayList  Object method
IEnumerator  Ie = al. GetEnumerator ();
While (ie. MoveNext ())
{
The Console. Write (ie. Curret. ToString () + " " );
}

// the third kind of traversal   ArrayList  Object method
I forgot, it's like   Use   An attribute of an ArrayList object that returns the number of elements in the object.

And then using the index  
For (int  I = 0; I< The Count. I++)
{
The Console. Write (al [I] the ToString () + " " );
}


Related articles: