How to use ArrayList classes in Java _java

Source: Internet
Author: User
Tags memory usage

Use of ArrayList classes in Java

1, what is ArrayList

ArrayList is the legendary dynamic array, which, in MSDN, is a complex version of array that provides some of the following benefits:
Dynamic addition and reduction of elements
Implements the ICollection and IList interfaces
Flexibility to set the size of an array

2. How to use ArrayList

The simplest example:

ArrayList List = new ArrayList ();
for (int i=0;i <10;i++)//Add 10 int element to 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 additional elements
List.add (I+20);
Int32[] values = (int32[]) List.toarray (typeof (Int32));//return array contained in ArrayList

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

3. ArrayList important methods and properties

1) Builder

The ArrayList provides three constructors:
public ArrayList ();
The default constructor, which initializes an internal array with the default (16) Size
Public ArrayList (ICollection);
Constructs with a ICollection object and adds the elements of the collection to the ArrayList
public ArrayList (int);
Initializes an internal 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 a ArrayList-thread-synchronized encapsulation.
If you are using an instance that is not thread-synchronized, you need to manually call lock to keep the thread synchronized when multithreaded access, for example:
ArrayList list = new ArrayList ();
//...
Lock (list. SyncRoot///When ArrayList is not threaded, the SyncRoot attribute is itself, but in order to satisfy the SyncRoot definition of ICollection, here is the use of SyncRoot to keep the source code normative
{
List. Add ("Add a Item");
}

If you use the Arraylist.synchronized method to return an instance, then you do not have to consider the problem of thread synchronization, the instance itself is thread-safe, in fact ArrayList internally implements an internal class that guarantees thread synchronization, arraylist.synchronized returns this Instance of a class in which each property is used with the lock keyword to keep the thread synchronized.

3 Count property and Capacity property

The Count property is the number of elements that are currently ArrayList, and this property is read-only.
The capacity property is the maximum number that the ArrayList can contain at the moment, and can be set manually, but an exception is thrown when set to less than the count value.

4 Add, AddRange, Remove, RemoveAt, RemoveRange, Insert, Insertrange

These methods are more 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 deletes an element by referring to the element itself.
The RemoveAt method is used to delete an element by index value to remove
RemoveRange is used to delete a batch of elements by specifying the index to start and the number of deletions to delete
Inserts are used to add an element to the specified position, and the elements behind the list move back in sequence
Insertrange is used to add a batch of elements starting at the specified location, and the elements behind the list move back in sequence

In addition, there are several similar methods:
The clear method clears 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 burden, you can view MSDN, the above is more careful

5) Trimsize method

This method is used to pin the ArrayList to the size of the actual element, and when the dynamic array element is determined not to be added, this method can be invoked to free up free memory.

6) ToArray method

This method copy the ArrayList elements 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);
Adding different types of elements to an array

Object[] values = List.toarray (typeof (object)); That's right
String[] values = (string[]) List.toarray (typeof (String)); Error

and arrays are different, because you can convert to an object array, so it's not wrong to add elements of the same type to ArrayList, but when you call the ArrayList method, you either pass the type or object type that all elements can transform correctly, Otherwise, an exception that cannot be transformed will be thrown.

5, the best use of ArrayList recommendations

In this section we discuss the difference between ArrayList and arrays, and the efficiency of ArrayList.
(1) ArrayList is a complex version of array
The ArrayList internally encapsulates an object-type array, which, in general terms, has no essential difference, and even ArrayList many methods, such as index, INDEXOF, Contains, Sort is the corresponding method of directly calling array on the basis of an internal array.
(2) The effect of the internal object type
For a generic reference type, this part of the impact is not very large, but for value types, adding and modifying elements to ArrayList will cause boxing and unboxing operations, and frequent operations may affect some 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 bear part of the loss of efficiency, but this part of the loss is not very large.
(3) Array expansion
This is a factor that affects the efficiency of the ArrayList more greatly.
Whenever a method of adding elements, such as Add, AddRange, Insert, Insertrange, is performed, the internal array is checked for insufficient capacity, and if so, it will reconstruct an array at twice times the current capacity, copy the old elements into the new array, and discard the old array. In this critical point of the expansion operation, it should be more effective effect.
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 passes through:
16*2*2*2*2 = 256
The four-time expansion will meet the final requirements, so if you start with:
ArrayList List = new ArrayList (210);
The way to create ArrayList, not only reduces the 4 times of array creation and copy operations, but also reduces memory usage.

Example 2:30 elements are expected to create a ArrayList:
ArrayList List = new ArrayList (30);
In the execution process, the addition of 31 elements, then the array will expand to 60 elements of the size, and there will be no new elements to add in, and there is no call to the Trimsize method, then there are 1 expansion operations, and waste 29 element size space. If this is the case, use:
ArrayList List = new ArrayList (40);
Then everything was settled.
Therefore, it is an important way to improve the efficiency of ArrayList using the correct prediction of possible elements and the Trimsize method when appropriate.
(4) Frequent calls to IndexOf, contains and other methods (Sort, BinarySearch and other methods optimized, not only) caused by the loss of efficiency
First, let's be clear, ArrayList is a dynamic array, which does not include algorithms that are accessed quickly by key or value, so actually calling IndexOf, contains, and so on, is a simple loop to perform to find the element. So frequent calls to such methods are not faster than you write the loop on your own and slightly optimized, and if this is the case, it is recommended to 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!");

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

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

.........

The first way to traverse a ArrayList object
foreach (Object o in AL)
{
Console.Write (o.tostring () + "");
}

The second method of traversing the ArrayList object
IEnumerator Ie=al. GetEnumerator ();
while (ie. MoveNext ())
{
Console.Write (ie. Curret.tostring () + "");
}

The third method of traversing ArrayList objects
I forgot, it's like taking advantage of an attribute of a ArrayList object that returns the number of elements in this object.

And then use the index
for (int i=0;i<count;i++)
{
Console.Write (Al[i]. ToString () + "");
}

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.