Java arrayList traversal of the four methods and the use of the arrayList class in Java

  • 2020-04-01 04:24:07
  • OfStack

Java arrayList traversal of the four methods and the use of the 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());
    }
    //Methods 3
    for(String tmp:list){
      System.out.println(tmp);
    }
    //Methods 4
    for(int i = 0;i < list.size(); i ++){
      System.out.println(list.get(i));
    }
  }
}

  Ps: usage of the ArrayList class in Java

1. What is an ArrayList

ArrayList is the legendary dynamic Array, or complex version of Array as it is called in MSDN, and it offers the following benefits:

Dynamic addition and subtraction of elements

ICollection and IList interface are implemented

Flexible array size Settings

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 sixth element
for( int i=0;i <3;i++ ) //I'm going to add three more elements
List.Add(i+20); 
Int32[] values = (Int32[])List.ToArray(typeof(Int32));// return ArrayList Contained array 

This is a simple example that does not include all of the ArrayList methods, but reflects the most common usage of ArrayList

3. Important methods and properties of ArrayList

1) constructor

ArrayList provides three constructors:
Public ArrayList ();
The default constructor initializes the inner array at the default size (16)
Public ArrayList (ICollection);
Construct it with an ICollection object and add 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 a wrapper around the thread synchronization of the ArrayList.

If you use a non-thread-synchronized instance, you need to manually call the lock to keep the threads synchronized during multi-threaded access, for example:


ArrayList list = new ArrayList(); 
//... 
lock( list.SyncRoot ) // when ArrayList When wrapping for non-threads 

The SyncRoot attribute is itself, but to satisfy the SyncRoot definition of ICollection,

Again, SyncRoot is used to keep the source code regular


{ 
list.Add(  " Add a Item "  ); 
}

If you use the ArrayList. Synchronized method returns an instance of, so you don't have to consider the problem of thread synchronization, the instance itself is thread-safe, actually inside the ArrayList implements a guarantee thread synchronization inner class, ArrayList. Synchronized return is an instance of the class, it's the lock key of each attribute is used to guarantee the thread synchronization.

3) Count attribute and Capacity attribute

The Count attribute, which is read-only, is the number of elements currently contained in the ArrayList.
The Capacity property is the maximum amount that an ArrayList can currently contain. This property can be set manually, but an exception is thrown when set to less than the value of Count.

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 Remove an element by reference to the element itself
The RemoveAt method is used to remove an element, by index value
RemoveRange is used to remove a batch of elements, by specifying the number of indexes to start with and the number of deletions
Insert is used to add an element to the specified location, with the elements following the list moving back in turn
InsertRange is used to add a batch of elements from the specified location, with the elements following the list moving back 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 out if an object is in the list

I'm not going to bother you with the rest, but you can look at MSDN, which is more detailed

5) TrimSize method

This method is used to fix the ArrayList to the size of the actual element and is called to free up free memory when the dynamic array element is determined not to be added.

6) ToArray method

This method copies the elements of the ArrayList into a new array.

4. ArrayList and array conversion

Case 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 of converting from an ArrayList to an array 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)); //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 is not wrong to add different types of elements to the ArrayList. However, when the ArrayList method is called, it should either pass the type that all elements can be converted correctly or the Object type, or it will throw an exception that cannot be transformed.

5. Suggestions for the best use of ArrayList

In this section, we will discuss the difference between an ArrayList and an array, and the efficiency of an ArrayList

1) ArrayList is a complex version of Array

ArrayList internally encapsulates an array of type Object, which is not fundamentally different from an array in a general sense

To the size of the actual element, this method can be called to free up free memory when the dynamic array element is determined not to be added.

6) ToArray method

This method copies the elements of the ArrayList into a new array.

4. ArrayList and array conversion

Case 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 of converting from an ArrayList to an array 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)); //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 is not wrong to add different types of elements to the ArrayList. However, when the ArrayList method is called, it should either pass the type that all elements can be converted correctly or the Object type, or it will throw an exception that cannot be transformed.

5. Suggestions for the best use of ArrayList

In this section, we will discuss the difference between an ArrayList and an array, and the efficiency of an ArrayList

1) ArrayList is a complex version of Array

ArrayList internally encapsulates an Array of type Object. In a general sense, it is not fundamentally different from an Array. Many methods of ArrayList, such as Index, IndexOf, Contains, Sort, etc., call the corresponding method of Array directly on the basis of an internal Array.

2) the influence of internal Object type

For general reference types, this part of the impact is not very big, but for value types, adding and modifying elements to the ArrayList causes boxing 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 effect. Unless you don't use it, you will have to bear some loss of efficiency, which is not very large.

3) array expansion

This is a factor that has a great impact on the efficiency of ArrayList.
Whenever the Add, AddRange method of adding elements, Insert and InsertRange, will check the internal array capacity is not enough, if it is, it will double the current capacity to rebuild an array to Copy the old elements to the new array, then discarding the old array, in this critical point of expansion, is affecting the efficiency of the comparison should be.

Example 1: for example, a data that may have 200 elements is dynamically added to an ArrayList that is created with the default size of 16 elements and will go through:

16 * 2 * 2 * 2 * 2 = 256

Four times of capacity expansion will meet the final requirements, so if the beginning with:

ArrayList List = new ArrayList(210);
ArrayList is created in a way that not only reduces group creation and Copy operations by four times, but also reduces memory usage.

Example 2: an ArrayList is created with an expectation of 30 elements:

ArrayList List = new ArrayList(30);

In the process of execution, 31 elements are added, then the array will expand to the size of 60 elements, and there will be no new elements added in this time, and there is no TrimSize method called, then there is one expansion operation, and wasted 29 element size space. If so, use:

ArrayList List = new ArrayList(40);

Then everything is settled.
Therefore, correctly estimating the possible elements and calling TrimSize method when appropriate is an important way to improve the use efficiency of ArrayList.

4) frequently invoke methods such as IndexOf, Contains, etc. (Sort, BinarySearch, etc.)

The method is optimized, not in this column) caused by the efficiency loss
First of all, we have to be clear, the ArrayList is a dynamic array, it does not include through Key or Value algorithm of fast access, so in fact call IndexOf, the Contains method is to perform simple cycle to look for the element, so often call this kind of method does not write cycle than yourself and make a little optimization to fast, if has this aspect of the requirements, recommend the use of Hashtable or SortedList collection of Key/Value pair.


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


Related articles: