ArrayList class in Java

Source: Internet
Author: User

1. What is ArrayList
ArrayList is the legendary dynamic array, which, in MSDN parlance, is a complex version of array that provides some of the following benefits:
Dynamic increase and decrease of elements
Implements the ICollection and IList interfaces
Flexibility to set the size of the array

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);
//.. Program to do some processing
List.removeat (5);//Remove the 6th element
for (int i=0;i <3;i++)//Add 3 more elements
List.add (I+20);
Int32[] values = (int32[]) List.toarray (typeof (Int32));//Returns an array containing the ArrayList

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

3. ArrayList important methods and properties
1) Constructors
The ArrayList provides three constructors:
public ArrayList ();
The default constructor, which initializes the inner array with the default (16) Size
Public ArrayList (ICollection);
Constructs a ICollection object and adds 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 the encapsulation of a ArrayList thread synchronization.
If you are using an instance of non-thread synchronization, you need to manually call lock to maintain thread synchronization when multithreaded access, for example:
ArrayList list = new ArrayList ();
//...
Lock (list. SyncRoot)//When ArrayList is a non-threaded wrapper, the SyncRoot property is itself, but in order to satisfy the SyncRoot definition of ICollection, the SyncRoot is used to maintain the normative nature of the source code.
{
List. Add ("Add a Item");
}

If you use the instance returned by the Arraylist.synchronized method, then you do not have to worry about thread synchronization, the instance itself is thread-safe, in fact, ArrayList internal implementation of a guaranteed thread synchronization internal class, Arraylist.synchronized returned is this Instance of a class, each of which uses the lock keyword to ensure thread synchronization.

3) The Count property and the Capacity property
The Count property is the number of elements currently contained in the ArrayList, and this property is read-only.
The capacity property is the maximum number that can be contained by the current ArrayList, which is set manually, but throws an exception when set to less than the count value.

4) Add, AddRange, Remove, RemoveAt, RemoveRange, Insert, Insertrange
These methods are more similar
The Add method adds 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 that is removed by a reference to the element itself
The RemoveAt method is used to delete an element by using the index value to remove
RemoveRange is used to delete a batch of elements by specifying the starting index and the number of deletions to delete
Inserts are used to add an element to the specified position, and the elements following the list move backward in turn
Insertrange is used to add a batch of elements starting at the specified position, and the elements behind the list move backwards

In addition, there are several similar methods:
The clear method is used to clear all existing elements
The Contains method is used to find an object that is not in the list

The rest of me is not a liability, you can view the MSDN, above the more careful
5) Trimsize method
This method is used to pin the ArrayList to the actual element size, and when the dynamic array element is determined not to be added, this method can be called to free up free memory.
6) ToArray method
This method copy the elements of ArrayList into 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);

Two methods for converting from ArrayList to arrays are described above

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)); That's right
String[] values = (string[]) List.toarray (typeof (String)); Error

Arrays are different because they can be converted to an object array, so it is not an error to add elements of various types to the ArrayList, but when calling the ArrayList method, 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, ArrayList best use Suggestion
In this section we discuss the differences between ArrayList and arrays, and the efficiency of ArrayList.
1) ArrayList is a complex version of array
ArrayList internally encapsulates an array of type Object, which, in general terms, has no essential difference

To the actual element size, you can call this method to free up free memory when the dynamic array element is determined not to be added.
6) ToArray method
This method copy the elements of ArrayList into 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);

Two methods for converting from ArrayList to arrays are described above

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)); That's right
String[] values = (string[]) List.toarray (typeof (String)); Error

The

and the array are not the same, because you can convert to the object arrays, so adding different types of elements to ArrayList is not an error, but when you call the ArrayList method, 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, ArrayList best use recommendation  
This section discusses the differences between ArrayList and arrays, and the efficiency of ArrayList  
1) ArrayList is a complex version of array  
ArrayList internally encapsulates an array of type Object, which, in general terms, has no essential difference, even ArrayList many methods, such as index, INDEXOF, Contains, Sort is the corresponding method of calling array directly on the basis of an internal array.  
2) The influence of the object type inside the  
for general reference types, this part of the effect is not very large, but for value types, adding and modifying elements into the ArrayList will cause the boxing and unpacking operations, Frequent operations can affect part of the efficiency.  
But for most people, most applications use arrays of value types.  
There is no way to eliminate this effect, unless you do not use it, you will have to take part of the efficiency loss, but this part of the loss will not be very large.  
3) array expansion  
This is a factor that has a greater impact on ArrayList efficiency.  
the method of adding elements, such as Add, AddRange, Insert, Insertrange, and so on, will check the capacity of the internal array if it is not enough, and if so, it will reconstruct an array at twice times the current capacity, and copy the old elements into the new array. Then discard the old array, at this point in the expansion operation, it should be compared to the impact of efficiency.  
Example 1: For example, a data that may have 200 elements is dynamically added to a ArrayList created with the default 16 element size, which will go through:  
16*2*2*2*2 = 256 
Four times the expansion will meet the final requirements, then if you start with:  
ArrayList List = new ArrayList (ArrayList);  
. Not only reduces the array creation and copy operations by 4 times, but also reduces memory usage.

Example 2:30 elements are expected to create a ArrayList:
ArrayList List = new ArrayList (30);
In the execution process, added 31 elements, then the array will be expanded to 60 elements of the size, and this time there will be no new elements added, and there is no call to the Trimsize method, then there is 1 expansion of the operation, and wasted 29 element size space. If this is the case, use:
ArrayList List = new ArrayList (40);
Then everything has been solved.
Therefore, it is an important way to improve the efficiency of ArrayList use to correctly estimate the possible elements and call the Trimsize method when appropriate.
4) frequent calls to IndexOf, contains and other methods (Sort, BinarySearch, etc.)

Efficiency loss due to the optimization of the law
First, let's make it clear that ArrayList is a dynamic array that does not include algorithms that are accessed quickly through key or value, so actually calling IndexOf, contains, and so on is a simple loop that executes to find the element, So frequent calls to such methods are not faster than writing loops yourself and optimizing them, and if so, we recommend using a collection of key-value pairs such as Hashtable or SortedList.
ArrayList al=new ArrayList ();

Al. ADD ("how");
Al. ADD ("is");
Al. ADD ("you!");

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

Al. ADD (1.2);
Al. ADD (22.8);

End

(RPM) ArrayList class in Java

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.