List初始化 :
List<String> list = new ArrayList<String>();
list.add("Hello");
这两行在做什么事情?
源代码:
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
transient Object[] elementData;
结论:ArrayList的底层是用数组来存储数据。 构造了一个空数组。
如果是有參,传递数组:
List<String> strList = new ArrayList<String>();
strList.add("World");
List<String> list = new ArrayList<String>(strList);
源代码:
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();//将集合转换为数组并保存
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
// 元素数组的类型如果不是Object数组类型,则拷贝赋值
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
List添加元素(可添加null)
第一种:
List<String> strList = new ArrayList<String>();
strList.add("World");
源代码:
public boolean add(E e) {
//判断数组长度是否足够,否则扩容
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
//判断
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
// 判断默认数组长度与当前长度
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// 如果当前最小下标大于数组的长度,则数组自增长
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// 获取原来数组的长度
int oldCapacity = elementData.length;
// 新的数组长度等于原来的长度加上原来长度位移1
int newCapacity = oldCapacity + (oldCapacity >> 1);
// 如果新的数组长度小于最小的长度
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
// 如果新的长度超出了数组设定的最大的长度
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// 扩容
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;
}
// 用于计数
protected transient int modCount = 0;
// 数组最大的长度
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
private static final int DEFAULT_CAPACITY = 10;
第二种(针对某个位置添加):
strList.add(2, "Java");
源代码:
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++;
}
// 校验是否越界
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
List获取元素
第一种:普通for循环
for(int index = 0;index
List遍历元素
第一种:迭代器
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
String str = iterator.next();
System.out.println(str);
}
迭代器是一种很特殊的遍历。因为集合内部存储结构不同,以及遍历的顺序不一样,
所以这个类需要到实现类中进行实现。
源代码:
public Iterator<E> iterator() {
return new Itr();
}
// 内置迭代器的实现类 实现接口Iterator 并重写其方法
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
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];
}
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();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
// 判断是否为遍历修改,如果数量不一致,则抛出异常
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
List删除元素
第一种根据下标删除:
String strs = list.remove(0);
源代码:
public E remove(int index) {
// 判断下表是否越界
rangeCheck(index);
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;
}
private void rangeCheck(int index) {
// 如果下标大于等于实际的长度则抛出越界异常
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
第二种根据元素删除:
boolean flag = list.remove("World");
源代码:
public boolean remove(Object o) {
if (o == null) {//如果被删除的元素等于null,则找到元素的下表,并移除
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
//所以如果是移除相同的对象即元素值相同(需重写equals方法)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
private void fastRemove(int index) {
modCount++;
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
}
List更新元素
代码:
// 返回被替换的字符串
String orginal = list.set(0, "God");
源代码:
public E set(int index, E element) {
// 判断是否越界
rangeCheck(index);
// 获取原来的数据
E oldValue = elementData(index);
// 赋值更新的数据
elementData[index] = element;
//返回原来的数据
return oldValue;
}
// 通过下标获取数据
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
//判断数组范围
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}