Arraylist usage)

Source: Internet
Author: User

1. What is arraylist?
9? J xui 'B! @ XbguestArraylist 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
O8w + T % vvg '; B lkguestThe simplest example:
Ttqqc5 | guestArraylist list = new arraylist ();E-learning zone "wk2p9 [j1i9 ~ P
For (INT I = 0; I <10; I ++) // Add 10 int elements to the array.E Learning zone # _ r! @ 8qrc-vw
List. Add (I );
U8ac "I ^ Z; loguest//..ProgramDo some processingE Learning zone [{C * RJ
List. removeat (5); // remove the 6th Elements
M ,? K9e ++? | GuestFor (INT I = 0; I <3; I ++) // Add three more elements.E Learning zone ?! E3's B/n1zvs's
List. Add (I + 20 );E Learning zone! R k # k'og {M-
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 e Learning zone & u7g t3d $ }_* _ j
(1) constructor
4Z |! Zerqguest arraylist provides three constructors: e Learning zone @. c0v % R?} Gk5tq
Public arraylist ();
; g % ej7w k5tymguest default constructor. The internal array E-learning zone 7tr5rf1 ~ Wj4g "A
Public arraylist (icollection);
A/^ ol5q2xguest is constructed using an icollection object, and the elements of this set are added to arraylist
7y _ 8ue9] y * g9sk "~) Cguest Public arraylist (INT);
3 H l] gp! C "an2qguest uses the specified size to initialize an internal array.

(2) attributes of issynchronized and arraylist. synchronized Method E study zone F7 {wwz) U, c3 [B
the issynchronized attribute indicates whether the current arraylist instance supports thread synchronization, while the arraylist. the synchronized static method returns the encapsulation of the arraylist thread synchronization. E Zone 4 {~ V'rx
if a non-thread synchronization instance is used, you need to manually call lock to maintain thread synchronization during multi-thread access. For example: E-learning zone U; r5q, V6} OJ
arraylist list = new arraylist ();
f1e7t. p/x + poguest //... E Zone 9 | j * B ^ sh7k * A
lock (list. syncroot) // when arraylist is not packaged in a thread, the syncroot attribute is actually its own. However, to meet the syncroot definition of icollection, syncroot is used to maintain Source Code normalization
^ $ j9 \}? Eguest {< span style = "display: none"> E-learning zone hsr s "?. N8 {+ j2f
list. add ("add a item"); e Learning zone 3jl * q }# e
}

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
_ {A # zf7m; AH (iguestThe Count attribute is the number of elements contained in the current arraylist. This attribute is read-only.
B m "Bx (_ 2 K/B !} F'sguestThe 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
Q0tuq; h9w3cguestThese methods are similar.E Learning zone + M (L "i3k5mb
The add method is used to add an element to the end of the current list.E-learning zone, [(vedt {
The addrange method is used to add a batch of elements to the end of the current list.
Z? 0r & E/O (jk. r5rguestThe remove method is used to delete an element by referencing the element itself.E Learning zone $ S6 @, Z + qg9dd
The removeat method is used to delete an element and use the index value to delete it.
Y! X/G ^ Uh _/a1inav & eguestRemoverange is used to delete a batch of elements by specifying the start index and the number of deleted elements.E Learning zone KF (E (G _
Insert is used to add an element to a specified position, and the elements following the list are moved in turnE Learning Zone A % LD | Zi Di
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:Sx8r # W. z-GBv7P
The clear method is used to clear all existing elements.
Gfgr. u4kguestThe 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.
~ & Oqq) W i5gguest(5) trimsize Method
; KJ) | "um7yxguestThis 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.
Zo1bj "~ J ~ Ty; I-qguest(6) toarray MethodE-learning zone [9t. Y, W, J "Q
This method copies the arraylist elements to a new array.

4. arraylist and array Conversion
7m0gi X. d7za + hguestExample 1:E-learning zone * n vook R
Arraylist list = new arraylist ();E Learning zone ~ Gv2xa z gq I + R"
List. Add (1 );E-learning zone u1nl: {f9kr
List. Add (2 );
4z7gk/UJ 's1z % B, [GuestList. Add (3 );

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

Example 2:E-learning zone 0bs/y * ul8u9 '. p
Arraylist list = new arraylist ();
Lkj4 '7ad? 4G [GuestList. Add (1 );Sv pz # uofq .'
List. Add (2 );
2c "} 5d9s F + O '2q] 7A $ kguestList. Add (3 );

Int32 [] values = new int32 [list. Count];
: E8 ~ K; A B7 'jguestList. copyto (values );

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

Example 3:
-W (hzh7o/O & Q2 ^. L (fguestArraylist list = new arraylist ();E-learning zone) J "vzr _. u
List. Add ("string ");E-learning zone, lypwwt m3 \ Oe?
List. Add (1 );
M8wa; sq % ', | # nlguest// Add different types of elements to the array

Object [] values = List. toarray (typeof (object); // correctE-learning zone U, WD qnnp, X
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 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 E-learning zone te. X5] yofi
In this section, we will discuss the differences between arraylist and array, and the efficiency of arraylist.
Ih! A: B Ju &} guest (1) arraylist is a complex version of array.
) '(U cc v + N z} guest 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. E Learning zone? Z! O3f '\
(2) impact of internal Object Types
7u9 \ MV &] + G % zguest 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.
';? Qn. MBC ^ e0z2nguest But for most people, most applications use value-type arrays. E Learning zone & sm) k) p * P:} 'h2dx
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. E Learning zone! D; ey # y * ^
(3) array resizing
0jjl # P; qva {guest This is a factor that significantly affects arraylist efficiency. E Learning zone R ,? O, ^ # {0l: S
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. E-learning zone EAB * i7fh "P/T
Example 1: for example, a data with 200 elements may be dynamically added to an arraylist created with 16 default element sizes:
3u # ed0n) Di, nguest 16*2*2*2*2 = 256
Q (_ HRM! @ V xguest Four resizing operations will meet the final requirement: E-learning zone NDC c9ome (\-'?, H
Arraylist list = new arraylist (210 );
! Odpp-R # U (Q ^ + rguest 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: E-learning zone Fe. J! L7a; B f ~
Arraylist list = new arraylist (30 ); E-learning zone 6he (u} # J/Fv
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:E-learning zone eua1f 6CM + E
Arraylist list = new arraylist (40 ); E Learning zone? Vi) xg7s
So everything is done.
Tffz4 @ * P ~; Baguest Therefore, correct estimation of possible elements and calling the trimsize method when appropriate is an important way to improve the efficiency of arraylist. E-learning zone TR "YY; V & nw3l
(4) efficiency loss caused by frequent calls of indexof, contains, and other methods (sort, binarysearch, and other methods have been optimized, not listed here)
S id8kp4bwguest First, we need to make it clear that arraylist is a dynamic array, which does not include quick access through key or value. Algorithm Therefore, calling indexof, contains, and other methods is actually a simple loop of execution to find 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.
U8aw & zlmguest Arraylist Al = new arraylist ();

Al. Add ("how ");
P/T, R. UF @ e0cguestAl. Add ("are ");
$ LP | P! A \ * wguestAl. Add ("you! ");

ALS. Add (100 );E Learning zone: 5ody3? * ^ G, VX "^" BW
ALS. Add (200 );E-learning zone t5dyx. _ y; pfel
ALS. Add (300 );

ALS. Add (1.2 );
/A: U ~ N: C, \ guestALS. Add (22.8 );

.........

// The first method to traverse the arraylist objectE-learning zone * cfy ~ *~ 7D "K; UA! T2o
Foreach (Object o in Al)E Learning zone % Y q p o} WFM? 0 p
{E-Learning Zone Q-DN-V %] "L
Console. Write (O. tostring () + "");E Learning zone {v ~. B. X-K
}

// Method 2 for traversing the arraylist object
(G, rdie_cmguestIenumerator Ie = Al. getenumerator ();E-learning zone wi % ncln ~] |
While (ie. movenext ())E-learning zone mhvj1kux
{E-learning zone-VRV + cz + L
Console. Write (ie. curret. tostring () + "");E Zone 8 _ & | "uu5 @ '$ ar |}
}

// Method 3 for traversing the arraylist objectE-learning zone UI,] 4er7m4.7
I forgot, as if using an attribute of the arraylist object, it returns the number of elements in this object.

Then, using the indexE-learning zone-VC ~ -Wo: F1s
For (INT I = 0; I <count; I ++)E-learning zone w4gd2qj @
{
"M ,~ \ | Z $ q (uxguestConsole. Write (Al [I]. tostring () + "");
Ih0? O \ s5uguest}
6k _ % o8 [& E * s \ uguest

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.