Java Basics: ArrayList use

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:
A. Dynamic addition and reduction of elements
B. ICollection and IList interfaces are implemented
C. 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 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

This section discusses the differences between ArrayList and arrays, and the efficiency of ArrayList  
1) ArrayList is a complex version of the array  
ArrayList internally encapsulates an array of type Object, which, in general terms, has no intrinsic difference, and 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 and other methods have been optimized, not excluded) caused by the loss of efficiency

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);

using the ArrayList class
The ArrayList class implements the list interface, and the list collection implemented by the ArrayList class uses an array structure to hold the object. The advantage of the array structure is that it facilitates quick random access to the collection, and if you frequently need to access the objects in the collection based on the index location, it is more efficient to use the list collection implemented by the ArrayList class. The disadvantage of an array structure is that inserting an object at the specified index location and deleting the specified index location object is slow, if you frequently need to insert an object into the specified index location of the list collection, or to delete the object at the specified index of the list collection. The use of the list collection implemented by the ArrayList class is less efficient, and the smaller the index position of the inserted or deleted object is less efficient, because when an object is inserted at the specified index position, the specified index position and all subsequent objects are moved backward one bit, as shown in 1. When you delete an object at the specified index location, all objects after the specified index position are moved forward one bit at a time, as shown in 2. If there are a large number of objects after the specified index position, the operational efficiency of the collection is severely affected.

This is because the list collection implemented with the ArrayList class has the disadvantage of inserting and deleting objects, and not using the ArrayList class to instantiate the list collection at the time of writing routine 06 o'clock, here is an example of an imitation that often requires random access to objects in the collection.
In writing this example, using the random () method of the Java.lang.Math class, this method can get a double random number less than 10, multiply the random number by 5 and then cast to an integer, will get a 0 to 4 integer, And randomly accesses the object of that index position in the list collection implemented by the ArrayList class, with the following code:
Src\com\mwq\testcollection.java Key Code:
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); Index position is 0
List.add (b); Index position is 1
List.add (c); Index position is 2
List.add (d); Index position is 3
List.add (e); Index position is 4
System.out.println (List.get ((int) (Math.random () * 5))); Simulating random access to objects in a collection
}

Examples of exercises I have in practice:

1  PackageCode; 2 Importjava.util.ArrayList; 3 ImportJava.util.Iterator; 4  Public classSimpleTest {5    6    7   Public Static voidMain (String []args) {8     9ArrayList List1 =NewArrayList (); TenList1.add ("One");  OneList1.add ("the");  AList1.add ("three");  -List1.add ("Four");  -List1.add ("Five");  theList1.add (0, "zero");  -System.out.println ("<--list1 has >" + list1.size () + "elements");  -System.out.println ("Content in <--list1:" + List1 + "-");  -      +ArrayList List2 =NewArrayList ();  -List2.add ("Begin");  + List2.addall (List1);  AList2.add ("End");  atSystem.out.println ("<--list2 has >" + list2.size () + "elements");  -System.out.println ("Content in <--list2:" + List2 + "-");  -      -ArrayList List3 =NewArrayList ();  - List3.removeall (List1);  -System.out.println ("Does one exist in the <--list3:" + (List3.contains ("one")? " Yes: "no") + "-");  in      -List3.add (0, "same element");  toList3.add (1, "same element");  +System.out.println ("<--list3 has >" + list3.size () + "elements");  -System.out.println ("Content in <--list3:" + list3 + "-");  theSystem.out.println (the index of the first occurrence of the same element in <--list3 is "+ list3.indexof (" same element ") +"-");  *System.out.println (the index of the last occurrence of same element in <--list3 is "+ list3.lastindexof (" same element ") +"--");  $     Panax Notoginseng      -System.out.println ("<--using iterator interface to access list3->");  theIterator it =List3.iterator ();  +    while(It.hasnext ()) { AString str =(String) it.next ();  theSystem.out.println ("Elements in <--list3:" + list3 + "-");  +   }   -      $System.out.println ("<--changes the same element in List3 to another element-->");  $List3.set (0, "another element");  -List3.set (1, "another element");  -System.out.println ("<--convert List3 to array--");  the     //Object [] array = (object[]) List3.toarray (new Object[list3.size ()]);  -Object [] Array =List3.toarray (); Wuyi       for(inti = 0; i < Array.Length; i + +){   theString str =(String) array[i];  -System.out.println ("array[" + i + "] =" +str);  Wu      }        -         AboutSystem.out.println ("<---empty list3->");  $ list3.clear ();  -System.out.println ("<--list3" is empty: "+ (List3.isempty ()?") Yes: "no") + "-");  -System.out.println ("<--list3 has >" + list3.size () + "elements");  -      A   //System.out.println ("Hello world!");  +  }   the}

Java Basics: ArrayList use

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.