[Add to favorites] How to Use arraylist in. net

Source: Internet
Author: User
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:
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. removeat (5); // remove the 6th Elements
For (INT I = 0; I <3; I ++) // Add three more elements.
List. Add (I + 20 );
Int32 [] values = (int32 []) List. toarray (typeof (int32); // returns the array contained in arraylist

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 arraylist. Synchronized static method

Returns the encapsulation of the arraylist thread synchronization.
If a non-thread synchronization instance is used, you need to manually call lock to maintain thread synchronization during multi-thread access. For example:
Arraylist list = new arraylist ();
//...
Lock (list. syncroot) // when arraylist is not packaged by a thread, the syncroot attribute is actually its own,

Syncroot meets the syncroot definition of icollection. syncroot is used to keep the source code standard.
{
List. Add ("add a item ");
}

If you use the instance returned by the arraylist. Synchronized Method, you do not need to consider the thread synchronization problem. This instance itself is

Thread security. In fact, arraylist implements an internal class to ensure thread synchronization, Which is returned by arraylist. synchronized.

It is an instance of this class. Every attribute in it uses the lock keyword to ensure thread synchronization.

****

However, using this method (arraylist. Synchronized) does not guarantee enumeration synchronization. For example, a thread is deleting or adding

When a collection item is added and another thread enumeration is performed at the same time, the enumeration will throw an exception. Therefore, when enumerating, you must explicitly use

Syncroot locks this set.

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, but when it is set to smaller than count

Value will cause an exception.

(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 elements.
The contains method is used to find that an object 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:
Arraylist list = new arraylist ();
List. Add (1 );
List. Add (2 );
List. Add (3 );

Int32 [] values = (int32 []) List. toarray (typeof (int32 ));

Example 2:
Arraylist list = new arraylist ();
List. Add (1 );
List. Add (2 );
List. Add (3 );

Int32 [] values = new int32 [list. Count];
List. copyto (values );

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

Example 3:
Arraylist list = new arraylist ();
List. Add ("string ");
List. Add (1 );
// Add different types of elements to the array

Object [] values = List. toarray (typeof (object); // correct
String [] values = (string []) List. toarray (typeof (string); // Error

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 you call the arraylist method, either pass the type or object type that all elements can be correctly transformed. Otherwise

Throw an exception that cannot be transformed.

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, or even

Many arraylist methods, such as index, indexof, contains, and sort, are directly called based on the internal array.

Method.
(2) impact of internal Object Types
For the general reference type, this part does not have a great impact, but for the value type, add and modify to the arraylist

Elements may cause packing and unpacking operations. Frequent operations may affect some of the 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 good.

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 rebuild an array with twice the current capacity, copy the old elements to the new array, and then discard the old array,

The expansion operation at this critical point may affect the efficiency.
Example 1: for example, if data with 200 elements is dynamically added to an arraylist created with 16 default element sizes

After:
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 60 elements, and no new elements will be added at this time.

And whether or not the trimsize method is called, there will be one resizing operation, and the space of 29 elements is wasted. If

When:
Arraylist list = new arraylist (40 );
So everything is done.
Therefore, correct estimation of possible elements and calling the trimsize method when appropriate are important to improve the efficiency of arraylist usage.

Channels.
(4) effects of frequent calls to methods such as indexof and contains (sort, binarysearch, and other methods have been optimized, not listed here)

Rate loss
First, we need to make it clear that arraylist is a dynamic array and does not include algorithms that can be quickly accessed through keys or values.

Calling indexof, contains, and other methods on is a simple loop of execution to find the elements, so frequent calls of such methods are not

The write loop is faster and slightly optimized. If you have such requirements, we recommend that you use a set of key-value pairs such as hashtable or sortedlist.

.
Arraylist Al = new arraylist ();

Al. Add ("how ");
Al. Add ("are ");
Al. Add ("you! ");

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

ALS. Add (1.2 );
ALS. Add (22.8 );

.........

// The first method to traverse the arraylist object
Foreach (Object o in Al)
{
Console. Write (O. tostring () + "");
}

// Method 2 for traversing the arraylist object
Ienumerator Ie = Al. getenumerator ();
While (ie. movenext ())
{
Console. Write (ie. curret. tostring () + "");
}

// Method 3 for traversing the arraylist object
I forgot, as if using an attribute of the arraylist object, it returns the number of elements in this object.

Then, using the index
For (INT I = 0; I <count; I ++)
{
Console. Write (Al [I]. tostring () + "");
}

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.