
底层数据结构是数组,线程不安全。
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);
}
在调用 add 方法的时候,会去判断下是否需要扩容,扩容的主要逻辑就是上面的代码,每次扩容为之前的 1.5 倍, 左移右移的写法 看着好高级啊。
ArrayList list=new ArrayList(10);
list.add(“1”);
list.add(“2”);
list.add(1,”3”);
这时候 list 的顺序是什么样的?
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
想起一个简单粗暴的梗,在比赛中超过了第几名,你就是第几名:)
集合的遍历
关于 arrayList 的思考?
底层结构是链表,线程不安全
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
public E remove(int index) {
checkElementIndex(index);
return unlink(node(index));
}
底层是数据,线程安全,好多特性都和 ArrayList 一样,没有什么好说的。
为什么他要 可以保证线程安全?
//添加
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
//修改
public synchronized E set(int index, E element) {
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
//删除
public synchronized boolean removeElement(Object obj) {
modCount++;
int i = indexOf(obj);
if (i >= 0) {
removeElementAt(i);
return true;
}
return false;
}
看了这段代码,好像也没什么了不起的啊,把涉及到集合的值的修改方法全部用 Synchornized 修饰,简单粗暴。