Four methods of java arrayList traversal and usage of ArrayList class in Java
package com.test;import java.util.ArrayList;import java.util.Iterator;import java.util.List;public class ArrayListDemo { public static void main (String args[]){ List<String> list = new ArrayList< String>(); list.add("luojiahui"); list.add("luojiafeng"); //Method 1 Iterator it1 = list.iterator(); while(it1.hasNext()){ System.out.println (it1.next()); } //Method 2 for(Iterator it2 = list.iterator(); it2.hasNext();){ System.out.println(it2.next()); } //Method 3 for(String tmp:list){ System.out.println(tmp); } //Method 4 for(int i = 0;i < list.size(); i ++){ System.out.println(list. get(i)); } }}ps: Usage of ArrayList class in Java
1. What is ArrayList
ArrayList is the legendary dynamic array. In the MSDN term, it is a complex version of Array. It provides the following benefits:
Dynamically increase and decrease elements
Implement ICollection and IList interfaces
Flexible setting of array size
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 element for( int i=0;i <3;i++ ) //Add 3 more elements List.Add(i+20); Int32[] values = (Int32[]) List.ToArray(typeof(Int32));//Return 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 commonly used usage of ArrayList
3. Important methods and properties of ArrayList
1) Constructor
ArrayList provides three constructors:
public ArrayList();
The default constructor will initialize the internal array with the default (16) size
public ArrayList(ICollection);
Constructed with an ICollection object and add elements of the collection to the ArrayList
public ArrayList(int);
Initialize the internal array with the specified size
2) IsSynchronized property and ArrayList.Synchronized method
The IsSynchronized property indicates whether the current ArrayList instance supports thread synchronization, while the ArrayList.Synchronized static method returns an ArrayList thread synchronization encapsulation.
If you use non-threaded synchronization instances, you need to call lock manually to keep thread synchronization when accessing multi-threads, for example:
ArrayList list = new ArrayList(); //... lock( list.SyncRoot ) //When ArrayList is wrapped in non-thread
The SyncRoot property is actually itself, but in order to satisfy the SyncRoot definition of ICollection,
Here we still use SyncRoot to maintain the standardization of the source code
{ list.Add( "Add a Item" ); }If you use the instance returned by the ArrayList.Synchronized method, you don’t need to consider the issue of thread synchronization. This instance itself is thread-safe. In fact, ArrayList implements an internal class that ensures thread synchronization. The returned class by ArrayList.Synchronized Instance, each property in it uses the lock keyword to ensure thread synchronization.
3) Count attribute and Capacity attribute
The Count property is the number of elements currently contained in ArrayList, and this property is read-only.
The Capacity property is the maximum number that ArrayList can currently contain. This property can be set manually, but an exception will be raised when set to less than the Count value.
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 and delete it through the reference of the element itself.
The RemoveAt method is used to delete an element and delete it by indexing the value.
RemoveRange is used to delete a batch of elements, which is deleted by specifying the starting index and the number of deletes.
Insert is used to add an element to the specified position, and the elements behind the list are moved backwards in turn.
InsertRange is used to add a batch of elements from the specified position, and the elements behind the list are moved backwards 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 won't be burdened with the rest. You can check MSDN, which is more carefully mentioned above.
5) TrimSize method
This method is used to fix the ArrayList to the size of the actual element. When the dynamic array element is determined not to be added, this method can be called to free up the spare memory.
6) ToArray method
This method Copy the ArrayList element 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);
The above introduces two methods of converting from ArrayList to array
Example 3:
ArrayList List = new ArrayList(); List.Add( "string" ); List.Add( 1 ); //Add different types of elements into 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, so it will not make any mistake to add different types of elements into an ArrayList. However, when calling the ArrayList method, either pass a type or Object type that can be correctly converted by all elements, otherwise An exception that cannot be transformed will be thrown.
5. Best advice on using ArrayList
In this section, we will discuss the difference between ArrayList and array, as well as the efficiency of ArrayList
1) ArrayList is a complex version of Array
ArrayList encapsulates an array of Object type. In general, it has no essential difference from an array, even
Determine the size of the actual element. When the dynamic array element is determined not to be added, this method can be called to free up the spare memory.
6) ToArray method
This method Copy the ArrayList element 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);
The above introduces two methods of converting from ArrayList to array
Example 3:
ArrayList List = new ArrayList(); List.Add( "string" ); List.Add( 1 ); //Add different types of elements into 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, so it will not make any mistake to add different types of elements into an ArrayList. However, when calling the ArrayList method, either pass a type or Object type that can be correctly converted by all elements, otherwise An exception that cannot be transformed will be thrown.
5. Best advice on using ArrayList
In this section, we will discuss the difference between ArrayList and array, as well as the efficiency of ArrayList
1) ArrayList is a complex version of Array
ArrayList encapsulates an Object-type array. In general, it has no essential difference from an array. Even many methods of ArrayList, such as Index, IndexOf, Contains, Sort, etc., are directly based on the internal array. Call the corresponding method of Array.
2) The influence of internal Object type
For general reference types, this part has not a big impact, but for value types, adding and modifying elements into ArrayList will cause packing and unboxing operations, and frequent operations may affect some efficiency.
But for most people, most applications use arrays of value types.
There is no way to eliminate this impact. Unless you don’t use it, you will have to bear part of the efficiency loss, but this part of the loss will not be huge.
3) Array expansion
This is a factor that has a greater impact on the efficiency of ArrayList.
Whenever you execute Add, AddRange, Insert, InsertRange and other methods to add elements, it will check whether the capacity of the internal array is insufficient. If so, it will rebuild an array at twice the current capacity and copy the old element to the new. In the array, then discard the old array. The expansion operation at this critical point should be more influencing efficiency.
Example 1: For example, if a data with 200 elements is dynamically added to an ArrayList created with the default size of 16 elements, it will pass:
16*2*2*2 = 256
Four expansions will meet the final requirements, so if:
ArrayList List = new ArrayList( 210 );
Create an ArrayList in the way will not only reduce the 4-time array creation and Copy operations, but also reduce memory usage.
Example 2: An ArrayList is created with an expected 30 elements:
ArrayList List = new ArrayList(30);
During the execution process, if 31 elements are added, the array will be expanded to the size of 60 elements, and no new elements will be added in at this time. And if the TrimSize method is called, then there will be an expansion operation. , and wasted 29 element-sized space. If at this time, use:
ArrayList List = new ArrayList(40);
Then everything is solved.
Therefore, correctly estimating possible elements and calling the TrimSize method at appropriate times is an important way to improve the efficiency of using ArrayList.
4) Frequently call IndexOf, Contains and other methods (Sort, BinarySearch and other squares
The efficiency loss caused by the method is optimized, not in this column) First of all, we need to make it clear that ArrayList is a dynamic array, which does not include algorithms that are quickly accessed through Key or Value, so in fact, calling IndexOf, Contains and other methods is simple to execute. Loops to find elements, so frequently calling such methods is not faster than writing loops yourself and optimizing them slightly. If you have 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("are"); al.Add("you!");al.Add(100);al.Add(200); al.Add(300);al.Add(1.2);al.Add(22.8);