Detailed description of the ArrayList class in Java and detailed description of javaarraylist

Source: Internet
Author: User

Detailed description of the ArrayList class in Java and detailed description of javaarraylist

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

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.

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 methods such as IndexOf and Contains (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 );

5) ToArray Method
This method copies the ArrayList elements to a new array.

Use the ArrayList class
The ArrayList class implements the List interface. The List set implemented by the ArrayList class uses an array structure to save objects. The advantage of the array structure is that it facilitates fast Random Access to the set. If you often need to access objects in the Set Based on the index location, it is more efficient to use the List set implemented by the ArrayList class. The disadvantage of the array structure is that it is slow to insert objects to the specified index location or delete objects at the specified index location. If you need to insert objects to the specified index location of the List set, you can also delete objects at the specified index position in the List set. Using the List set implemented by the ArrayList class is less efficient, and the smaller the index location of the inserted or deleted objects, the lower the efficiency, the reason is that when an object is inserted to a specified index location, all objects at the specified index location and after the specified index location are moved one bit backward, as shown in 1. When you delete an object at the specified index location, all objects after the specified index location are moved one by one, as shown in figure 2. If a large number of objects exist after the specified index location, the operation efficiency of the set will be seriously affected.

 

This is because the List set implemented by the ArrayList class has the disadvantage of inserting and deleting objects. The List set is not instantiated by the ArrayList class when the routine 06 is compiled, the following is an example of imitating objects that often require random access to the collection.
Java. lang. the random () method of the Math class can be used to obtain a random number of the double type less than 10, multiply the random number by 5, and then forcibly convert it to an integer, an integer ranging from 0 to 4 is obtained, and the objects at the index location in the List set implemented by the ArrayList class are randomly accessed. The Code is as follows:
Key code of src \ com \ mwq \ TestCollection. Java:
Public static void main (String [] args ){
String a = "A", B = "B", c = "C", d = "D", e = "E ";
List <String> list = new ArrayList <String> ();
List. add (a); // The index position is 0.
List. add (B); // The index location is 1.
List. add (c); // The index location is 2.
List. add (d); // The index location is 3.
List. add (e); // The index location is 4.
System. out. println (list. get (int) (Math. random () * 5); // simulate random access to objects in the Set
}

My actual practice example:

1 package code; 2 import java. util. arrayList; 3 import java. util. iterator; 4 public class SimpleTest {5 6 7 public static void main (String [] args) {8 9 ArrayList list1 = new ArrayList (); 10 list1.add ("one "); 11 list1.add ("two"); 12 list1.add ("three"); 13 list1.add ("four"); 14 list1.add ("five"); 15 list1.add (0, "zero"); 16 System. out. println ("<-- list1 in total>" + list1.size () + "elements"); 17 System. out. println ("< -- Content in list1: "+ list1 +" --> "); 18 19 ArrayList list2 = new ArrayList (); 20 list2.add (" Begin "); 21 list2.addAll (list1 ); 22 list2.add ("End"); 23 System. out. println ("<-- list2>" + list2.size () + "elements"); 24 System. out. println ("<-- Content in list2:" + list2 + "-->"); 25 26 ArrayList list3 = new ArrayList (); 27 list3.removeAll (list1); 28 System. out. println ("<-- Does list3 contain one:" + (list3.contains ("one ")? "Yes": "no") + "-->"); 29 30 list3.add (0, "same element"); 31 list3.add (1, "same element "); 32 System. out. println ("<-- list3 in total>" + list3.size () + "elements"); 33 System. out. println ("<-- Content in list3:" + list3 + "-->"); 34 System. out. println ("<-- the index of the first same element in list3 is" + list3.indexOf ("same element") + "-->"); 35 System. out. in println ("<-- the last index of the same element in list3 is" + list3.lastIndexOf ("same element") + "-->"); 36 37 38 System. out. println ("<-- use the Iterator interface to access list3->"); 39 Iterator it = list3.iterator (); 40 while (it. hasNext () {41 String str = (String) it. next (); 42 System. out. println ("<-- elements in list3:" + list3 + "-->"); 43} 44 45 System. out. println ("<-- modify the same element in list3 to another element -->"); 46 list3.set (0, "another element"); 47 list3.set (1, "another element"); 48 System. out. println ("<-- convert list3 to an array -->"); 49 // Object [] Array = (Object []) list3.toArray (new Object [list3.size ()]); 50 Object [] array = list3.toArray (); 51 for (int I = 0; I <array. length; I ++) {52 String str = (String) array [I]; 53 System. out. println ("array [" + I + "] =" + str); 54} 55 56 System. out. println ("<--- clear list3->"); 57 list3.clear (); 58 System. out. println ("<-- list3 is empty:" + (list3.isEmpty ()? "Yes": "no") + "-->"); 59 System. out. println ("<-- list3 in total>" + list3.size () + "elements"); 60 61 // System. out. println ("hello world! "); 62} 63}

 

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.