ArrayList

1. The structure of ArrayList

2. What is ArrayList?
  • An ArrayList is a data structure that behaves like a computerarray but also implements the ability todynamically grow the size of the array as needed. ArrayList structure can grow and shrink the size of the array in response to the addition or deletion of elements.
  • Using an ArrayList provides a program with the ability to access data objects with an index number instantly instead of having to walk through an entire sequence of data to find an address.
  • ArrayList is not thread-safe, it is used in single thread.
3. The definition of ArrayList

java.lang.Object --> java.util.AbstractCollection<E> --> java.util.AbstractList<E>  --> java.util.ArrayList<E>

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable

  • ArrayList extends AbstractList and implements List.
  • ArrayList implement RandomAccess(nothing), it support random access function.
  • ArrayList implement Cloneable(Object.clone), it can be clone.
  • ArrayList implement java.io.Serializable interface, which meansArrayList supportserialization.
4. Private property

private transient Object[] elementData;   // Array

private int size;         // The size of the ArrayList.

transient

             When JVM in its life cycle, object exist. Java Serialization make the object can be stored  after JVM stop running.

  • transient
  • transient variable value can not be saved after object serilized.
  • transient can only be used to restrict variable, not method and class. Local variable can not be defined as transient.
  • static variable can not be serialized no matter it is transient or not.

 1 public class UserInfo implements Serializable {
 2     private static final long serialVersionUID = 996890129747019948L;
 3     private String name;
 4     private transient String psw;
 5 
 6     public UserInfo(String name, String psw) {
 7         this.name = name;
 8         this.psw = psw;
 9     }
10 
11     public String toString() {
12         return "name=" + name + ", psw=" + psw;
13     }
14 }
15 
16 public class TestTransient {
17     public static void main(String[] args) {
18         UserInfo userInfo = new UserInfo("Jone", "123456");
19         System.out.println(userInfo);
20         try {
21             // Serialization,transient property can not be serialized
22             ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(
23                     "UserInfo.out"));
24             o.writeObject(userInfo);
25             o.close();
26         } catch (Exception e) {
27             // TODO: handle exception
28             e.printStackTrace();
29         }
30         try {
31             // read UserInfo.out
32             ObjectInputStream in = new ObjectInputStream(new FileInputStream(
33                     "UserInfo.out"));
34             UserInfo readUserInfo = (UserInfo) in.readObject();
35             // read psw is null
36             System.out.println(readUserInfo.toString());
37         } catch (Exception e) {
38             // TODO: handle exception
39             e.printStackTrace();
40         }
41     }
42 }

5. Constructor in ArrayList

ArrayList() // 10

ArrayList(int capacity)

ArrayList(Collection<? extends E> collection)

6.  Arrays.copyof()  vs  System.arraycopy()

public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {                                                                                                                             
      T[] copy = ((Object)newType == (Object)Object[].class)                                                                                                                                                                                               
        ? (T[]) new Object[newLength]                                                                                                                                                                                                                                       
          : (T[]) Array.newInstance(newType.getComponentType(), newLength);                                                                                                                                                                    
      System.arraycopy(original, 0, copy, 0,                                                                                                                                                                                                                              
                       Math.min(original.length, newLength));                                                                                                                                                                                                          
      return copy;                                                                                                                                                                                                                                                               
  }                                                                                                                                                                                                                                                                                      
 

Arrays.copyof() create a new Array with lengthnewLength, then callSystem.arraycopy(), copy the elements from the originalArrays to newArrays.

7. Functions in ArrayList

// Collection中定义的API
boolean             add(E object)
boolean             addAll(Collection<? extends E> collection)
void                     clear()
boolean             contains(Object object)
boolean             containsAll(Collection<?> collection)
boolean             equals(Object object)
int                        hashCode()
boolean             isEmpty()
Iterator<E>        iterator()
boolean             remove(Object object)
boolean             removeAll(Collection<?> collection)
boolean             retainAll(Collection<?> collection)
int                       size()
<T> T[]               toArray(T[] array)
Object[]              toArray()


// AbstractCollection中定义的API
void                add(int location, E object)
boolean        addAll(int location, Collection<? extends E> collection)
E                    get(int location)
int                  indexOf(Object object)
int                  lastIndexOf(Object object)
ListIterator<E>     listIterator(int location)
ListIterator<E>     listIterator()
E                   remove(int location)
E                   set(int location, E object)
List<E>        subList(int start, int end)



// ArrayList新增的API
Object             clone()
void                 ensureCapacity(int minimumCapacity)  // Every time add one element , the capacity will enlarge to (oldcapacity*3/2)+1
void                 trimToSize()
void                 removeRange(int fromIndex, int toIndex)



### ArrayList 的使用方法和特性 #### 存储性能 ArrayList 是基于动态数组实现的列表[^2]。在底层,它使用一个数组来存储元素,并在需要时自动扩容。这种设计使得 ArrayList 在进行按索引访问时性能非常高,但在插入和删除操作上可能表现不如链表。 #### 特性 1. **动态扩容**:ArrayList 在添加新元素时,如果当前数组已满,它会创建一个更大的数组(通常是原大小的 1.5 倍),然后将原数组的元素复制到新数组中。这种机制虽然避免了频繁的扩容,但在进行大批量元素添加时,扩容操作可能导致性能下降。 2. **随机访问**:由于底层使用数组存储,ArrayList 支持通过索引直接访问元素,时间复杂度为 O(1),因此非常适合频繁的随机读取操作。 3. **顺序存储**:ArrayList 中元素的存储是连续的数组位置,任何中间位置的插入或删除操作都需要移动元素,因此插入或删除操作的时间复杂度为 O(n)[^2]。 #### 使用场景 ArrayList 非常适合需要频繁随机访问元素的场景,而不适合频繁进行插入和删除操作的场景。 #### 示例用法 以下是一个简单的 ArrayList 使用示例: ```java import java.util.ArrayList; public class ArrayListExample { public static void main(String[] args) { // 创建一个ArrayList ArrayList<String> list = new ArrayList<>(); // 添加元素 list.add("Apple"); list.add("Banana"); list.add("Cherry"); // 访问元素 System.out.println("Element at index 1: " + list.get(1)); // 插入元素 list.add(1, "Apricot"); System.out.println("List after insertion: " + list); // 删除元素 list.remove(2); System.out.println("List after deletion: " + list); // 检查元素是否存在 boolean containsBanana = list.contains("Banana"); System.out.println("List contains 'Banana': " + containsBanana); } } ``` #### 性能分析 - **查找操作**:通过索引访问的时间复杂度为 O(1),因为可以直接定位数组中的位置。 - **插入/删除操作**:在末尾添加元素的时间复杂度为 O(1),但在中间或头部插入/删除元素时,时间复杂度为 O(n),因为需要移动数组中的元素。 - **扩容开销**:当数组容量不够时,ArrayList 需要进行扩容操作,扩容的时间复杂度为 O(n),因为所有元素需要被复制到新的数组中。 #### 线程安全 ArrayList 不是线程安全的。如果需要线程安全的列表,可以使用 Vector 或者使用 Collections.synchronizedList 方法来包装 ArrayList。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值