Java容器回顾
常用的容器
List 知识点
List 是按照一定顺序保存元素,他继承 Vector 对象, 用对象数组保存元素( Object[] ).
- ArrayList : 擅长根据索引 index 随机访问元素, 元素的插入和删除效率很低。
在指定位置插入元素,会使用 add(int index, E element) 方法。 执行步骤如下:
- 检查index是否越界.
- 根据新的长度 size+1 检查是否容量足够,如果不够,按照 oldCapacity + (oldCapacity+1) 进行扩容。
- 用系统方法拷贝index之前和之后的元素,方法为 System.arraycopy(elementData, index, elementData, index + 1, size - index);
- 在index所在位置设置新元素 element. elementData[index] = element;
- 把ArrayList 的长度 size 加 1;
在指定位置添加元素的方法
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++;
}
在指定位置删除元素的方法
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to be removed
* @return the element that was removed from the list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
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;
}
Map 知识点
HashMap 是允许 key 为 null 的。 原因是 HashMap 根据 key 计算hash值,而hash值的计算方式如下:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
可以看到,key 如果为null, 那么 hash值为0. 如果key不为null,就调用系统方法计算:
public native int hashCode();