ArrayList in Java and its uses

Source: Internet
Author: User

1, what is ArrayList ArrayList is the legendary dynamic array, using MSDN to say, is the complex version of the array, It offers some of the following benefits: Dynamic increase and decrease elements implement the ICollection and IList interfaces flexibly set the size of the array 2, how to use the ArrayList simplest example: ArrayList List = new ArrayList (); T 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 elements List.add (I+20); int32[] values = (int32[)) list.to Array (typeof (Int32));//Returns the ArrayList contains an array this is a simple example, although not all ArrayList methods are included, but can reflect the most common use of ArrayList 3, ArrayList important methods and properties 1) The constructor ArrayList provides three constructors: public ArrayList (); The default constructor, which initializes the internal array public ArrayList with the default (16) Size ( ICollection), constructed with a ICollection object, and adding the elements of the collection to Arraylistpublic ArrayList (int); Initializes the inner array with the specified size 2) The IsSynchronized property and the Arraylist.synchronized method IsSynchronized property indicates whether the current ArrayList instance supports thread synchronization.      The arraylist.synchronized static method returns a ArrayList thread-synchronous wrapper. If you are using an instance that is not thread-synchronized, you need to manually call lock to keep the thread in sync 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 of the Count property are the number of elements currently contained in 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 compare similar to the Add method for adding an element to the end of the current list 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, and a reference to the element itself is used to remove an element from the RemoveAt method. Remove RemoveRange by index value to delete a batch of elements, remove insert to add an element to the specified position by specifying the starting index and the number of deletions, and then move the element following the list backward Insertrange to add a batch of elements starting at the specified position. The elements that follow the list move backwards in turn, there are several similar methods: The Clear method is used to clear all existing elements contains method is used to find an object that is not in the list of the other I am not a burden, you can view MSDN, above the more careful 5) Trimsize party 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:arraylistList = new ArrayList (); List.add (1); List.add (2); List.add (3); int32[] values = new Int32[list.count];      List.copyto (values); Here are two examples of how to convert from ArrayList to arrays 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)); Errors and 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 transformed correctly, Otherwise, an exception that cannot be transformed will be thrown. 5, ArrayList Best Use Recommendations 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,    In the general sense, it does not have the essential difference to the group, even the many methods of ArrayList, such as index, INDEXOF, Contains, sort, etc. are directly called the corresponding method of array on the basis of the internal array. 2) The effect of the internal object type is not very significant for general reference types, but for value types, adding and modifying elements into ArrayList can cause boxing and unboxing, and frequent operations can 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 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. Whenever you do add, AddRange, Insert, Insertrange, and so on, the capacity of the internal array is not sufficient, and if it is, it will reconstruct an array at twice times the current capacity, copy the old elements toThe new array, and then discard the old array, at this critical point of the expansion operation, should be compared to the effect 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, will pass through: 16*2*2*2*2 = 2,564 times the expansion will meet the final requirements, then if you start with: ArrayList List =       New ArrayList (210), the way to create ArrayList, not only reduces the 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); During execution, 31 elements are added, and the array expands to the size of 60 elements, and no new elements are added at this time. And there is no call to the Trimsize method, then there are 1 expansion operations, and wasted 29 element size space. If this is the case, use: ArrayList List = new ArrayList (40); then everything is settled.     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 optimized, not excluded) caused by the loss of efficiency first, we want to be clear, ArrayList is a dynamic array, It does not include fast access through key or value algorithm, so actually call IndexOf, contains and other methods is to execute a simple loop to find the element, so frequent calls to this kind of method is not more than your own write loop and a little optimization to the fast, if there is this requirement, It is recommended to use 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 (+); al. ADD (+); al. ADD (+), AL. ADD (1.2); Al. ADD (22.8);.//The first way to traverse the ArrayList object is foreach (Object o in al) {Console.Write (o.tostring () + "");} The second way to traverse the ArrayList object is IEnumerator ie=al. GetenumErator (); while (ie. MoveNext ()) {Console.Write (ie. Curret.tostring () + "");} The third way to traverse the ArrayList object I forgot, as if it were a property of the ArrayList object that returns the number of elements in this object. Then in the use of the index for (int i=0;i<count;i++) {Console.Write ( Al[i]. ToString () + "");}

ArrayList in Java and purpose

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.