public HashSet() {
map = new HashMap<>();
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
public TreeSet() {
this(new TreeMap<>());
}
public boolean add(E e) {
return m.put(e, PRESENT)==null;
}
public Iterator<E> iterator() {
return new Itr();
}
public class TestIterator {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("張三");
list.add("李四");
list.add("王五");
list.add("趙六");
Iterator iterator = list.iterator();
while(iterator.hasNext()){
Object next = iterator.next();
//這裏使用集合的刪除方法,會產生異常java.util.ConcurrentModificationException
list.remove(next);
}
}
}
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
public boolean add(E e) {
modCount++;
add(e, elementData, size);
return true;
}
public E remove(int index) {
Objects.checkIndex(index, size);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
public boolean add(E e) {
modCount++;
add(e, elementData, size);
return true;
}
private void add(E e, Object[] elementData, int s) {
if (s == elementData.length)
elementData = grow();
elementData[s] = e;
size = s + 1;
}
private Object[] grow() {
return grow(size + 1);
}
private Object[] grow(int minCapacity) {
return elementData = Arrays.copyOf(elementData,
newCapacity(minCapacity));
}
private int newCapacity(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1); //這裏可以看到是擴容爲1.5倍
if (newCapacity - minCapacity <= 0) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
return Math.max(DEFAULT_CAPACITY, minCapacity); //這一行代碼是關鍵DEFAULT_CAPACITY的常量值被定義爲10
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return minCapacity;
}
return (newCapacity - MAX_ARRAY_SIZE <= 0) //Integer.MAX_VALUE - 8
? newCapacity
: hugeCapacity(minCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE)
? Integer.MAX_VALUE
: MAX_ARRAY_SIZE;
}
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
System.out.println("在最開始創建ArrayList對象,它的底層數組容量是:" + getCapacity(arrayList));
arrayList.add("張三");
System.out.println("在添加了一個元素後ArrayList對象,它的底層數組容量是:" + getCapacity(arrayList));
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三"); //這是第11個添加的元素,已經超過10個元素了
System.out.println("當添加第11個元素後,ArrayList做底層數組的擴容,擴容後的容量是:" + getCapacity(arrayList));
}
/**
* 通過反射的方式把ArrayList對象中的elementData數組拿出來看看現這個數組的長度
* @param obj 一個ArrayList的對象
* @return length 返回的是當前ArrayList對象底層數組的容量
*/
public static int getCapacity(Object obj){
int length = -1;
Class c = obj.getClass();
Field[] declaredFields = c.getDeclaredFields();
for (Field declaredField : declaredFields) {
if("elementData".equals(declaredField.getName())){
//打開私有訪問
declaredField.setAccessible(true);
try {
Object value = declaredField.get(obj);
Object o[] = (Object[]) value;
length = o.length;
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return length;
}
public E remove(int index) {
Objects.checkIndex(index, size);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
System.out.println("在最開始創建ArrayList對象,它的底層數組容量是:" + getCapacity(arrayList));
arrayList.add("張三");
System.out.println("在添加了一個元素後ArrayList對象,它的底層數組容量是:" + getCapacity(arrayList));
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三"); //這是第11個添加的元素,已經超過10個元素了
System.out.println("當添加第11個元素後,ArrayList做底層數組的擴容,擴容後的容量是:" + getCapacity(arrayList));
arrayList.remove(0);
System.out.println("刪除一個元素,此時元素只有" + arrayList.size() +",ArrayList做底層數組當前容量是:" + getCapacity(arrayList));
arrayList.remove(0);
System.out.println("刪除一個元素,此時元素只有" + arrayList.size() +",ArrayList做底層數組當前容量是:" + getCapacity(arrayList));
}
/**
* 通過反射的方式把ArrayList對象中的elementData數組拿出來看看現這個數組的長度
* @param obj 一個ArrayList的對象
* @return length 返回的是當前ArrayList對象底層數組的容量
*/
public static int getCapacity(Object obj){
int length = -1;
Class c = obj.getClass();
Field[] declaredFields = c.getDeclaredFields();
for (Field declaredField : declaredFields) {
if("elementData".equals(declaredField.getName())){
//打開私有訪問
declaredField.setAccessible(true);
try {
Object value = declaredField.get(obj);
Object o[] = (Object[]) value;
length = o.length;
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return length;
}
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
//再次調用自己的測試類進行驗證
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
System.out.println("在最開始創建ArrayList對象,它的底層數組容量是:" + getCapacity(arrayList));
arrayList.add("張三");
System.out.println("在添加了一個元素後ArrayList對象,它的底層數組容量是:" + getCapacity(arrayList));
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三");
arrayList.add("張三"); //這是第11個添加的元素,已經超過10個元素了
System.out.println("當添加第11個元素後,ArrayList做底層數組的擴容,擴容後的容量是:" + getCapacity(arrayList));
arrayList.remove(0);
System.out.println("刪除一個元素,此時元素只有" + arrayList.size() +",ArrayList做底層數組當前容量是:" + getCapacity(arrayList));
arrayList.remove(0);
System.out.println("刪除一個元素,此時元素只有" + arrayList.size() +",ArrayList做底層數組當前容量是:" + getCapacity(arrayList));
arrayList.trimToSize();
System.out.println("調用trimToSize方法後,此時元素只有" + arrayList.size() +",ArrayList做底層數組當前容量是:" + getCapacity(arrayList));
}
/**
* 通過反射的方式把ArrayList對象中的elementData數組拿出來看看現這個數組的長度
* @param obj 一個ArrayList的對象
* @return length 返回的是當前ArrayList對象底層數組的容量
*/
public static int getCapacity(Object obj){
int length = -1;
Class c = obj.getClass();
Field[] declaredFields = c.getDeclaredFields();
for (Field declaredField : declaredFields) {
if("elementData".equals(declaredField.getName())){
//打開私有訪問
declaredField.setAccessible(true);
try {
Object value = declaredField.get(obj);
Object o[] = (Object[]) value;
length = o.length;
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return length;
}
public LinkedList() {
}
transient int size = 0;
/**
* Pointer to first node.
*/
transient Node<E> first;
/**
* Pointer to last node.
*/
transient Node<E> last;
//調用add方法,它默認添加的位置是在鏈表的最後
public boolean add(E e) {
linkLast(e);
return true;
}
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++;
}
public void add(int index, E element) {
checkPositionIndex(index); //檢查指定的索引位置是否合法
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size;
}
void linkBefore(E e, Node<E> succ) {
// assert succ != null;
final Node<E> pred = succ.prev;
final Node<E> newNode = new Node<>(pred, e, succ);
succ.prev = newNode;
if (pred == null)
first = newNode;
else
pred.next = newNode;
size++;
modCount++;
}
Node<E> node(int index) {
// assert isElementIndex(index);
if (index < (size >> 1)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
remove方法,remove(int index)
public E remove(int index) {
checkElementIndex(index); //檢查要刪除元素位置
return unlink(node(index));
}
private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
E unlink(Node<E> x) {
// assert x != null;
final E element = x.item;
final Node<E> next = x.next;
final Node<E> prev = x.prev;
if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
x.item = null;
size--;
modCount++;
return element;
}
remove方法,remove(Object obj)
public boolean remove(Object o) {
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
static final int DEFAULT_INITIAL_CAPACITY = 1<<4;
static final int TREEIFY_THRESHOLD = 8; //樹化的閾值,從鏈表轉爲紅黑樹的長度
static final int MIN_TREEIFY_CAPACITY = 64; //這是表示最小樹化的容量
static final int UNTREEIFY_THRESHOLD = 6;
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
-
使用key的hashCode值調用hash()函數,干擾hash值,使得(key,value)更加均勻分佈table數組中(jdk1.8後的版本對hash()算法做了優化)
-
使用hash值與table.length-1進行按位與運算,保證index在[0,length-1]的範圍