Java Collection Framework (ii)--arraylist

Source: Internet
Author: User

Second, array list--arraylist

  

  1. Construction method

ArrayList is a dynamic array in Java, and the underlying implementation is an array of objects, except that the capacity of the array changes depending on the situation.

It has a constructor with an int type parameter, which expands the initialized array capacity according to the parameters passed in, this method is recommended, because if you know the capacity of the array beforehand, you can set the initial value, instead of waiting for each capacity enough to expand, reduce the number of arrays.copyof:

  

The implementation of many of its methods relies on the Arrays tool class, which is sufficient to reflect its close relationship with the array.

For example, there is a construction method with the Collection type, which is implemented as follows:

  

2. Common methods

1) TrimToSize method

Trims the capacity of this ArrayList instance to be the list's current size.

An application can use this operation to minimize the storage of a ArrayList instance.

This method can remove the extra space or memory occupied by ArrayList, because ArrayList will always have surplus after each expansion, if the array is large, the extra space occupied is larger, the memory is not enough to use this method.

2) Ensurecapacity method

public void ensurecapacity (int mincapacity)

Increases the capacity of this ArrayList instance, if-necessary, to-ensure-it can hold at least the number of element s specified by the minimum capacity argument.

In addition to the ability to define a given capacity in advance of initializing the ArrayList, this method can be used to increase the ArrayList initialization speed. Look at the following example:

1  Public Static voidMain (string[] args) {2         intn = 100000;3String str = "Hello google";4 5         //The ensurecapacity () method is not called to initialize the ArrayList object6arraylist<string> list =NewArraylist<>();7         LongStartTime =System.currenttimemillis ();8          for(inti = 0; I <= N; i++) {9 List.add (str);Ten         } One         LongEndTime =System.currenttimemillis (); ASystem.out.println ("Time:" + (Endtime-starttime) + "MS"); -  -         //Call the Ensurecapacity () method to initialize the ArrayList object theList =NewArraylist<>(); -StartTime =System.currenttimemillis (); - list.ensurecapacity (n); -          for(inti = 0; I < n; i++) { + List.add (str); -         } +EndTime =System.currenttimemillis (); ASystem.out.println ("Time:" + (Endtime-starttime) + "MS"); at}

The result is:

  

 3) IsEmpty method

Note This method is to determine whether it is empty, not whether it is null

 Public Boolean IsEmpty () {  return size = = 0;}

4) IndexOf, LastIndexOf and contain methods

The IndexOf method returns the index value of the first occurrence of the given object in the list (starting at 0), or 1 if it does not exist.

The LastIndexOf method returns the index value of the last occurrence of the given object in the list (starting with size-1) and returns 1 if it does not exist.

The contain method parameter is Object o, which determines if the list contains the given object, and returns True if the source code is as follows:

  

5) Add,get and set method

Three very simple methods, the difference is: The Add method is the array length +1, the given object is placed in the last position, the set method is to replace the element at the specified index position, the Get method is to get the element at the specified index position.

6) Remove method

Deleting an element at a specified index or specifying an element, not recommended, is more complex, and if you use this method, you should consider using LinkedList.

  3. Best Use Suggestion

1) ArrayList is a complex version of Array

ArrayList internally encapsulates an array of type Object, which, in general terms, has no intrinsic difference, and even many methods of ArrayList, such as Index, IndexOf, Contains, Sort The corresponding method of the array is called directly on the basis of the internal array.

2) The effect of the internal Object type

For general reference types, this part has little effect, but for value types, adding and modifying elements inside ArrayList can cause boxing and unboxing, and frequent operations may affect some of the efficiency.

3) Array expansion

This is a factor that has a great influence on the efficiency of ArrayList.

Whenever a method of adding elements, such as Add, AddRange, Insert, Insertrange, is checked, 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 into the new array, and 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 might have 200 elements dynamically added to a ArrayList created with the default 16 element size 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 (210) to create the ArrayList, not only reduce the array creation and Copy operations, but also reduce 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 is resolved.
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.

Special Acknowledgement:

1. Usage of ArrayList class in Java

2, "Thinking in Java"

3, "Core Java Volume I"

Java Collection Framework (ii)--arraylist

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.