List實作類【重要】
ArrayList:
底層是資料,查詢快,增刪慢
JDK1.2版本,運行效率快,執行緒不安全
LinkedList:
底層是鏈表,查詢慢,增刪快
Vector:
底層是資料,查詢快,增刪慢
JDK1.0版本,運行效率慢,執行緒安全
ArrayList
ArrayListDemo類是ArrayList的一些方法的使用,
package com.list;
import com.collection.Student;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
/**
* ArrayList的使用
* 存盤結構是陣列,查找快,增刪慢
*/
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList<>();
Student s1 = new Student("張三", 18);
Student s2 = new Student("李四", 20);
Student s3 = new Student("王二", 22);
//添加元素
arrayList.add(s1);
arrayList.add(s2);
arrayList.add(s3);
System.out.println("元素個數:"+arrayList.size());
//洗掉
// arrayList.remove(s1);
// System.out.println("洗掉之后個數:"+arrayList.size());
//元素遍歷
Iterator it = arrayList.iterator();
while (it.hasNext()) {
Student s =(Student) it.next();
System.out.println("迭代器遍歷:"+s.toString());
}
ListIterator listIterator = arrayList.listIterator();
while (listIterator.hasNext()) {
Student stu = (Student) listIterator.next();
System.out.println("串列迭代器遍歷:"+stu.toString());
}
//判斷
System.out.println("是否包含s1:" +arrayList.contains(s1));
System.out.println("是否為空:"+arrayList.isEmpty());
//查找
System.out.println("s2的下標:"+arrayList.indexOf(s2));
}
}
ArrarList原始碼分析【重點】
ArrayList實作了List介面,有序容器,就是存進去元素的順序和存的順序一致,允許null元素,底層是陣列,除了未實作同步,其他和Vector大致相同,
每個ArrayList都有一個容量(capacity),表示陣列的實際大小,當像容器添加元素的時候,如果容量不夠,容器會自動擴容,
變數名:
DEFAULT_CAPACITY:默認容量
EMPTY_ELEMENTDATA:空元素資料
DEFAULTCAPACITY_EMPTY_ELEMENTDATA:默認容量空元素資料
elementData:元素資料
size:元素個數
/**
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* Shared empty array instance used for empty instances.
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;
建構式
可以看到有3個建構式,如果ArrayList arrayList = new ArrayList<>();創建一個物件,就會呼叫無參構造,生成一個容量為0的arryList集合,
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public ArrayList(Collection<? extends E> c) {
Object[] a = c.toArray();
if ((size = a.length) != 0) {
if (c.getClass() == ArrayList.class) {
elementData = a;
} else {
elementData = Arrays.copyOf(a, size, Object[].class);
}
} else {
// replace with empty array.
elementData = EMPTY_ELEMENTDATA;
}
}
add(E e) 方法
當添加第一個元素的時候,因為初始為0,所以執行:ensureCapacityInternal(1)
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
自動擴容
每當向陣列中添加元素的時候,都會先檢查添加后元素個數是否超過陣列容量,如果超出,進行擴容,擴容通過 ensureCapacity(int minCapacity)方法實作,
陣列擴容的時候會將老陣列中的元素復制一份到新的陣列中,第一次擴容是從0到10,然后每次擴容大概是原容量的1.5倍,擴容代價很高,我們應盡量避免擴容,
/**
* Increases the capacity of this <tt>ArrayList</tt> instance, if
* necessary, to ensure that it can hold at least the number of elements
* specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
// any size if not default element table
? 0
// larger than default for default empty table. It's already
// supposed to be at default size.
: DEFAULT_CAPACITY;
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
/**
* The maximum size of array to allocate.
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
LinkedList原始碼分析【重點】
LinkedList底層是雙向鏈表
變數名
size:鏈表大小
first:第一個節點
last:最后一個節點
transient int size = 0;
/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
transient Node<E> first;
/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
transient Node<E> last;
Node是私有內部類
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
建構式
/**
* Constructs an empty list.
* 構造一個空串列,
*/
public LinkedList() {
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
add(E)方法
/**
* Appends the specified element to the end of this list.
* 將指定的元素追加到此串列的末尾,
* <p>This method is equivalent to {@link #addLast}.
*
* @param e element to be appended to this list
* @return {@code true} (as specified by {@link Collection#add})
*/
public boolean add(E e) {
linkLast(e);
return true;
}
/**
* Links e as last element.
* 將e鏈接為最后一個元素,
*/
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
在ArrayList的中間插入或洗掉一個元素,那串列中該元素往后的元素都會后移;而在LinkedList的中間插入或洗掉一個元素的開銷是固定的,
LinkedList不能隨機訪問,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/244824.html
標籤:java
上一篇:spring cloud hystrix 超時時間 使用方式
下一篇:Java開發入門
