Home > Java > javaTutorial > Four methods of java arrayList traversal and the usage of ArrayList class in Java

Four methods of java arrayList traversal and the usage of ArrayList class in Java

高洛峰
Release: 2017-01-22 15:59:21
Original
1701 people have browsed it

Four methods of java arrayList traversal and the usage 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");
    //方法1
    Iterator it1 = list.iterator();
    while(it1.hasNext()){
      System.out.println(it1.next());
    }
    //方法2
    for(Iterator it2 = list.iterator();it2.hasNext();){
       System.out.println(it2.next());
    }
    //方法3
    for(String tmp:list){
      System.out.println(tmp);
    }
    //方法4
    for(int i = 0;i < list.size(); i ++){
      System.out.println(list.get(i));
    }
  }
}
Copy after login

ps: The usage of the ArrayList class in Java

1. What is ArrayList

ArrayList is the legendary dynamic array. In MSDN terms, it is a complex version of Array. It provides the following benefits:

Dynamic increase and reduce elements

Implements the ICollection and IList interfaces

Flexibly 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++ ) //给数组增加10个Int元素
List.Add(i);
//..程序做一些处理
List.RemoveAt(5);//将第6个元素移除
for( int i=0;i <3;i++ ) //再增加3个元素
List.Add(i+20);
Int32[] values = (Int32[])List.ToArray(typeof(Int32));//返回ArrayList包含的数组
Copy after login

This is a simple example. Although it does not include all the methods of ArrayList, it can reflect the most common usage of ArrayList

3. Important methods and properties of ArrayList

1) Constructor

ArrayList provides three constructors:
public ArrayList();
The default constructor will be based on the default (16) to initialize the internal array
public ArrayList(ICollection);
Construct with an ICollection object and add the 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 will Returns a thread-synchronized encapsulation of an ArrayList.

If you use a non-thread synchronized instance, you need to manually call lock to maintain thread synchronization during multi-thread access, for example:

ArrayList list = new ArrayList();
//...
lock( list.SyncRoot ) //当ArrayList为非线程包装的时候
Copy after login

The SyncRoot attribute is actually itself, but in order to meet the SyncRoot definition of ICollection,

SyncRoot is still used here to maintain the standardization of the source code

{
list.Add( “Add a Item” );
}
Copy after login

If you use the instance returned by the ArrayList.Synchronized method, you do not need to consider the issue of thread synchronization. This instance itself is thread-safe. In fact, ArrayList implements an internal class that guarantees thread synchronization, ArrayList. Synchronized returns an instance of this class, and each attribute in it uses the lock keyword to ensure thread synchronization.

3) Count attribute and Capacity attribute

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

4) Add, AddRange, Remove, RemoveAt, RemoveRange, Insert, InsertRange

These methods are relatively similar

The Add method is used to add an element to the current list End
AddRange method is used to add a batch of elements to the end of the current list
Remove method is used to delete an element, by reference to the element itself
RemoveAt method is used to delete an element, by index value Delete
RemoveRange is used to delete a batch of elements by specifying the starting index and the number to delete
Insert is used to add an element to the specified position, and the elements at the end of the list are moved backwards in turn
InsertRange is used Add a batch of elements starting from the specified position, and the elements at the end of the list move backwards in sequence

In addition, there are several similar methods:

Clear method is used to clear all existing elements
Contains method is used to find out whether an object is in the list

I won’t go into details about the others one by one. You can check MSDN, which is explained in more detail

5) TrimSize method

This method is used to fix the ArrayList to the size of the actual elements. When the dynamic array elements are determined to be no longer added, this method can be called to release free memory.

6) ToArray method

This method copies 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));
Copy after login
Copy after login

Example 2:

ArrayList List = new ArrayList();
List.Add(1);
List.Add(2);
List.Add(3);
Int32[] values = new Int32[List.Count];
List.CopyTo(values);
Copy after login
Copy after login

The above introduces two methods of converting from ArrayList to array

Example 3:

ArrayList List = new ArrayList();
List.Add( “string” );
List.Add( 1 );
//往数组中添加不同类型的元素
object[] values = List.ToArray(typeof(object)); //正确
string[] values = (string[])List.ToArray(typeof(string)); //错误
Copy after login
Copy after login

It is different from an array because it can be converted to Object Array, so adding elements of different types to the ArrayList will not go wrong, but when calling the ArrayList method, you must either pass a type that can be converted correctly for all elements or an Object type, otherwise an exception that cannot be converted will be thrown.

5. Best suggestions for using ArrayList

In this section we will discuss the difference between ArrayList and array, as well as the efficiency issue of ArrayList

1) ArrayList is Array The complex version of

ArrayList internally encapsulates an array of type Object. In a general sense, it has no essential difference from an array, even down to the size of the actual elements. , when the dynamic array elements are determined to be no longer added, this method can be called to release the free memory.


6) ToArray method

This method copies 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));
Copy after login
Copy after login

Example 2:

ArrayList List = new ArrayList();
List.Add(1);
List.Add(2);
List.Add(3);
Int32[] values = new Int32[List.Count];
List.CopyTo(values);
Copy after login
Copy after login

The above introduces two methods of converting from ArrayList to array

Example 3:

ArrayList List = new ArrayList();
List.Add( “string” );
List.Add( 1 );
//往数组中添加不同类型的元素
object[] values = List.ToArray(typeof(object)); //正确
string[] values = (string[])List.ToArray(typeof(string)); //错误
Copy after login
Copy after login

和数组不一样,因为可以转换为Object数组,所以往ArrayList里面添加不同类型的元素是不会出错的,但是当调用ArrayList方法的时候,要么传递所有元素都可以正确转型的类型或者Object类型,否则将会抛出无法转型的异常。

5、ArrayList最佳使用建议

这一节我们来讨论ArrayList与数组的差别,以及ArrayList的效率问题

1)ArrayList是Array的复杂版本

ArrayList内部封装了一个Object类型的数组,从一般的意义来说,它和数组没有本质的差别,甚至于ArrayList的许多方法,如Index、IndexOf、Contains、Sort等都是在内部数组的基础上直接调用Array的对应方法。

2)内部的Object类型的影响

对于一般的引用类型来说,这部分的影响不是很大,但是对于值类型来说,往ArrayList里面添加和修改元素,都会引起装箱和拆箱的操作,频繁的操作可能会影响一部分效率。
但是恰恰对于大多数人,多数的应用都是使用值类型的数组。
消除这个影响是没有办法的,除非你不用它,否则就要承担一部分的效率损失,不过这部分的损失不会很大。

3)数组扩容

这是对ArrayList效率影响比较大的一个因素。
每当执行Add、AddRange、Insert、InsertRange等添加元素的方法,都会检查内部数组的容量是否不够了,如果是,它就会以当前容量的两倍来重新构建一个数组,将旧元素Copy到新数组中,然后丢弃旧数组,在这个临界点的扩容操作,应该来说是比较影响效率的。

例1:比如,一个可能有200个元素的数据动态添加到一个以默认16个元素大小创建的ArrayList中,将会经过:

16*2*2*2*2 = 256

四次的扩容才会满足最终的要求,那么如果一开始就以:

ArrayList List = new ArrayList( 210 );
的方式创建ArrayList,不仅会减少4次数组创建和Copy的操作,还会减少内存使用。

例2:预计有30个元素而创建了一个ArrayList:

ArrayList List = new ArrayList(30);

在执行过程中,加入了31个元素,那么数组会扩充到60个元素的大小,而这时候不会有新的元素再增加进来,而且有没有调用TrimSize方法,那么就有1次扩容的操作,并且浪费了29个元素大小的空间。如果这时候,用:

ArrayList List = new ArrayList(40);

那么一切都解决了。
所以说,正确的预估可能的元素,并且在适当的时候调用TrimSize方法是提高ArrayList使用效率的重要途径。

4)频繁的调用IndexOf、Contains等方法(Sort、BinarySearch等方

法经过优化,不在此列)引起的效率损失
首先,我们要明确一点,ArrayList是动态数组,它不包括通过Key或者Value快速访问的算法,所以实际上调用IndexOf、Contains等方法是执行的简单的循环来查找元素,所以频繁的调用此类方法并不比你自己写循环并且稍作优化来的快,如果有这方面的要求,建议使用Hashtable或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);
Copy after login

更多java arrayList遍历的四种方法及Java中ArrayList类的用法相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template