Java arraylist usage

Source: Internet
Author: User

Java arraylist usage

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 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:
Arraylist list = new arraylist ();
//...
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 the standardization of source code.
{
List. Add ("add a item ");
}

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 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 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.
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.