Differences between ArrayList and Array (continued)

Source: Internet
Author: User

ArrayList is a complex version of an array. The ArrayList class provides some functions that are provided in most Collections classes but not in the Array class. For example:

The Array capacity is fixed, and the ArrayList capacity is automatically expanded as needed. If the value of the ArrayList. Capacity attribute is changed, memory reallocation and element replication are performed automatically.

ArrayList allows you to add, insert, or remove a range of elements. In Array, you can only get or set the value of one element at a time.

Using Synchronized, you can easily create a synchronization version of ArrayList. Array will keep it until the user achieves synchronization.

 

 

Detailed explanation of the differences between ArrayList and Array: Full parsing of ArrayList

1. What is ArrayList?

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

Dynamically add and remove elements

ICollection and IList interfaces are implemented.

Flexible array size setting

 

2. How to Use ArrayList

The simplest example:

  1. ArrayList List =ArrayList ();
  2. (I = 0; I <10; I ++)
  3. List. RemoveAt (5 );
  4. (I = 0; I <3; I ++)
  5. Int32 [] values = (Int32 []) List. ToArray ((Int32 ));

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

3. Important ArrayList methods and attributes

(1) constructor

ArrayList provides three constructors:

Public ArrayList ();

The default constructor initializes the internal array with the default size (16 ).

Public ArrayList (ICollection );

Construct with an ICollection object and add the elements of the set to ArrayList

Public ArrayList (int );

Initializes an internal array with the specified size.

(2) IsSynchronized attributes and ArrayList. Synchronized Method

The IsSynchronized attribute indicates whether the current ArrayList instance supports thread synchronization, while the static method of ArrayList. Synchronized returns the encapsulation of a thread synchronization of ArrayList.

If a non-thread synchronization instance is used, you need to manually call lock to maintain thread synchronization during multi-thread access. For example:

 

  1. ArrayList list =ArrayList ();
  2.  
  3. (List. SyncRoot)
  4. {
  5. List. Add ("Add a Item ");
  6. }

If you use ArrayList. the instance returned by the Synchronized method does not need to be considered for 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. Every attribute in it uses the lock keyword to ensure thread synchronization.

However, use this method (ArrayList. synchronized) does not guarantee the synchronization of enumeration. For example, if one thread is deleting or adding collection items, and the other thread is enumerating at the same time, enumeration will throw an exception. Therefore, you must use SyncRoot to lock the set during enumeration.

Hashtable and ArrayList Use thread security in a similar way.

(3) Count and Capacity attributes

The Count attribute is the number of elements contained in the current ArrayList. This attribute is read-only.

The Capacity attribute is the maximum number that ArrayList can contain currently. You can manually set this attribute. However, when it is set to a value smaller than the Count value, an exception is thrown.

(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 by referencing the element itself.

The RemoveAt method is used to delete an element and use the index value to delete it.

RemoveRange is used to delete a batch of elements by specifying the start index and the number of deleted elements.

Insert is used to add an element to a specified position, and the elements following the list are moved in turn

InsertRange is used to add a batch of elements from the specified position, and the elements after the list are moved in turn

In addition, there are several similar methods:

The Clear method is used to Clear all existing meta-analytics Contains. It is used to find an object that is not in the list.

I don't have to worry about anything else. You can refer to MSDN for more details.

(5) TrimSize Method

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

(6) ToArray Method

This method copies the ArrayList elements to a new array.

4. ArrayList and array Conversion

Example 1:

 

  1. ArrayList List =ArrayList ();
  2. List. Add (1 );
  3. List. Add (2 );
  4. List. Add (3 );
  5.  
  6. Int32 [] values = (Int32 []) List. ToArray ((Int32 ));

Example 2:

  1. ArrayList List =ArrayList ();
  2. List. Add (1 );
  3. List. Add (2 );
  4. List. Add (3 );
  5.  
  6. Int32 [] values =Int32 [List. Count];
  7. List. CopyTo (values );

The preceding describes two methods for converting ArrayList to an array.

Example 3:

  1. ArrayList List =ArrayList ();
  2. List. Add ("");
  3. List. Add (1 );
  4.  
  5.  
  6. [] Values = List. ToArray (());
  7. [] Values = ([]) List. ToArray (());

It is different from an array. Because it can be converted to an Object array, adding different types of elements to the ArrayList will not cause errors. However, when the ArrayList method is called, either pass the type or Object type that all elements can be correctly transformed. Otherwise, an exception that cannot be transformed will be thrown.

5. Best use suggestions for ArrayList

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

(1) ArrayList is a complex version of Array.

ArrayList encapsulates an array of the Object type. In general, it has no essential difference with the array, and even many methods of ArrayList, for example, Index, IndexOf, Contains, and Sort all directly call the corresponding method of Array Based on the internal Array.

(2) impact of internal Object Types

For general reference types, this part does not have a great impact, but for value types, adding and modifying elements to ArrayList will cause packing and unpacking operations, frequent operations may affect some efficiency.

But for most people, most applications use value-type arrays.

There is no way to eliminate this impact. Unless you do not need it, you will have to bear part of the efficiency loss, but this part of the loss will not be very large.

(3) array resizing

This is a factor that significantly affects ArrayList efficiency.

Each time you execute Add, AddRange, Insert, InsertRange, and other methods to Add elements, check whether the internal array capacity is insufficient. If yes, it will re-build an array with twice the current capacity, Copy the old elements to the new array, and then discard the old array. At this critical point, the expansion operation, it may affect efficiency.

Example 1: for example, a data with 200 elements may be dynamically added to an ArrayList created with 16 default element sizes:

16*2*2*2*2 = 256

Four resizing operations will meet the final requirement:

ArrayList List = new ArrayList (210 );

Creating an ArrayList not only reduces the number of group creation and Copy operations, but also reduces memory usage.

Example 2: An ArrayList is created with 30 elements:

ArrayList List = new ArrayList (30 );

When 31 elements are added during execution, the array will be expanded to the size of 60 elements, and no new elements will be added at this time. Is there any call to the TrimSize method, so there is a resizing operation, and the space of 29 elements is wasted. If:

ArrayList List = new ArrayList (40 );

So everything is done.

Therefore, correct estimation of possible elements and calling the TrimSize method when appropriate is an important way to improve the efficiency of ArrayList.

(4) efficiency loss caused by frequent calls of IndexOf, Contains, and other methods (Sort, BinarySearch, and other methods have been optimized, not listed here)

First, we need to make it clear that ArrayList is a dynamic array, which does not include algorithms for fast access through keys or values, therefore, calling IndexOf, Contains, and other methods is actually a simple loop of execution to search for elements. Therefore, frequent calls to such methods are not faster than writing loops by yourself and are slightly optimized, if you have such requirements, we recommend that you use a set of key-value pairs, such as Hashtable or SortedList.

 

  1. ArrayList al =ArrayList ();
  2.  
  3. Al. Add ();
  4. Al. Add ();
  5. Al. Add ();
  6.  
  7. ALS. Add (100 );
  8. ALS. Add (200 );
  9. ALS. Add (300 );
  10.  
  11. ALS. Add (1.2 );
  12. ALS. Add (22.8 );
  13.  
  14. .........
  15.  
  16.  
  17. (OAl)
  18. {
  19. Console. Write (o. ToString () + );
  20. }
  21.  
  22.  
  23. IEnumerator ie = al. GetEnumerator ();
  24. (Ie. MoveNext ())
  25. {
  26. Console. Write (ie. Curret. ToString () + );
  27. }
  28.  
  29.  

I forgot, as if using an attribute of the ArrayList object, it returns the number of elements in this object.

Then, using the index

  1. (I = 0; I <Count; I ++)
  2. {
  3. Console. Write (al [I]. ToString () + );
  4. }

ArrayList provides a method to return read-only and fixed-size packages to a set. Array does not.

On the other hand, Array provides some flexibility that ArrayList does not have. For example:

You can set the lower limit of Array, but the lower limit of ArrayList is always zero.

Array can have multiple dimensions, while ArrayList is always one-dimensional.

Array of a specific type (excluding objects) has better performance than ArrayList. This is because the elements of ArrayList belong to the Object type. Therefore, when storing or retrieving value types, binning and unboxing are usually generated.

In most cases, an array can be replaced by ArrayList. It is easier to use and generally has the same performance as an array of the Object type.

Array is located in the System namespace; ArrayList is located in the System. Collections namespace.

The above summarizes the differences between ArrayList and Array.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.